Alex Rivera | Logout

jQuery/JavaScript "this" pointer confusion

Asked 2009-04-02T16:38:33.897
26

The behavior of "this" when function bar is called is baffling me. See the code below. Is there any way to arrange for "this" to be a plain old js object instance when bar is called from a click handler, instead of being the html element?

// a class with a method

function foo() {

    this.bar();  // when called here, "this" is the foo instance

    var barf = this.bar;
    barf();   // when called here, "this" is the global object

    // when called from a click, "this" is the html element
    $("#thing").after($("<div>click me</div>").click(barf));
}

foo.prototype.bar = function() {
    alert(this);
}
Edit
Report

2 Answers

6

There's a good explanation on this keyword in JavaScript available at QuirksMode.

answered 2009-04-02T16:58:10.450
3
answered 2009-04-02T16:59:40.477

Your Answer