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.
Yeah, this appears to be a common standard. Some coders use self, others use me. It's used as a reference back to the "real" object as opposed to the event.
It's something that took me a little while to really get, it does look odd at first.
I usually do this right at the top of my object (excuse my demo code - it's more conceptual than anything else and isn't a lesson on excellent coding technique):
edit: in spite of, nested functions within an object takes on the global window object rather than the surrounding object.
I think it actually depends on what are you going to do inside your
doSomething
function. If you are going to accessMyObject
properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things usingobject(MyObject)
properties.Just adding to this that in ES6 because of arrow functions you shouldn't need to do this because they capture the
this
value.One solution to this is to bind all your callback to your object with javascript's
bind
method.You can do this with a named method,
Or with an anonymous callback
Doing these instead of resorting to
var self = this
shows you understand how the binding ofthis
behaves in javascript and doesn't rely on a closure reference.Also, the fat arrow operator in ES6 basically is the same a calling
.bind(this)
on an anonymous function: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
this
becausethis
is 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:
this
is not unique in this respect:arguments
is the other pseudo variable that should be treated the same way — by aliasing.