On Apr 21, 02014, at 16:11, Reza Razavipour <[email protected]> wrote:
> I see a lot of code that does
> var self = this
>
> and then they use self instead of this for the duration of the function?
>
> Why and when would you use the above pattern?
Consider this:
var obj = {
method: function() {
// Right here, this == obj.
setTimeout(function () {
// Right here, this is something else.
}, 1000);
}
};
obj.method();
If you do this:
var obj = {
method: function() {
// Right here, this == obj.
var self = this;
setTimeout(function () {
// Right here, this is something else.
// But self is still lexically scoped — it’s the same as it was.
}, 1000);
}
};
obj.method();
The rules in javascript say that ‘this’ is dynamically scoped — generally, it’s
the object the method was called on, though you can use Function#call and
Function#apply and Function#bind to change it. For non-method functions like
callbacks, though, it’s something else. (Depending on strict mode and the
details of the call).
Because of what it does (too much!), Function#bind is slow. So we manually
enclose the ‘this’ in the parent scope to bind it lexically, rather than
dynamically. Since you can’t declare a new ‘this’ variable, we use self out of
convention — though that’s not universal. Any name will work.
Aria
signature.asc
Description: Message signed with OpenPGP using GPGMail
