Possible Duplicate:
JS: var self = this?
When looking at arbitrary code written in JavaScript (e.g. on GitHub), many developers use var self = this and then use self instead of this to reference the current object.
What is the rationale behind this approach?
The value of
thisis contextual. Writingvar self = thisis a way to save the value ofthisin one context so that it can be used in another.Example:
Prints:
Notice that the value of
thishas changed, but we can still refer to the original value usingself.This works because functions in JavaScript “close over” the variables in their lexical scope (which is just a more technical way of saying that the inner function can see variables declared in the outer function). This is why we write
var self = this; the variableselfis available to all inner functions, even if those functions don’t execute until long after the outer function has returned.