Using instance methods as callbacks for event handlers changes the scope of this from ‘My instance’ to ‘Whatever just called the callback’. So my code looks like this
function MyObject() { this.doSomething = function() { ... } var self = this $('#foobar').bind('click', function(){ self.doSomethng() // this.doSomething() would not work here }) }
It works, but is that the best way to do it? It looks strange to me.
This question is not specific to jQuery, but specific to JavaScript in general. The core problem is how to ‘channel’ a variable in embedded functions. This is the example:
This technique relies on using a closure. But it doesn’t work with
thisbecausethisis a pseudo variable that may change from scope to scope dynamically:What can we do? Assign it to some variable and use it through the alias:
thisis not unique in this respect:argumentsis the other pseudo variable that should be treated the same way — by aliasing.