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:
var abc = 1; // we want to use this variable in embedded functions
function xyz(){
console.log(abc); // it is available here!
function qwe(){
console.log(abc); // it is available here too!
}
...
};
This technique relies on using a closure. But it doesn't work with this
because this
is a pseudo variable that may change from scope to scope dynamically:
// we want to use "this" variable in embedded functions
function xyz(){
// "this" is different here!
console.log(this); // not what we wanted!
function qwe(){
// "this" is different here too!
console.log(this); // not what we wanted!
}
...
};
What can we do? Assign it to some variable and use it through the alias:
var abc = this; // we want to use this variable in embedded functions
function xyz(){
// "this" is different here! --- but we don't care!
console.log(abc); // now it is the right object!
function qwe(){
// "this" is different here too! --- but we don't care!
console.log(abc); // it is the right object here too!
}
...
};
this
is not unique in this respect: arguments
is the other pseudo variable that should be treated the same way — by aliasing.
self
as there is awindow.self
object and you could end up using that accidentally if you forget to declare your ownself
var (e.g. when moving some code around). This can be annoying to spot/debug. Better to use something like_this
. – Wendolynwendtthis
is dynamic in JavaScript. It is determined when function is called, not when it is declared." – Goodenself === this
. Therefore,self
in local contexts makes sense and is following the pattern. – Australasia