I run in to something that illustrates how I clearly don’t get it yet.
Can anyone please explain why the value of ‘this’ changes in the following?
var MyFunc = function(){ alert(this); var innerFunc = function(){ alert(this); } innerFunc(); }; new MyFunc();
In JavaScript,
thisrepresents the context object on which the function was called, not the scope in which it was defined (or the scope in which it was called). ForMyFunc, this references the new object being created; but forinnerFunc, it references the global object, since no context is specified wheninnerFuncis called.This tends to trip up those used to Java or similar OO languages, where
thisalmost always references an instance of the class on which the method being called is defined. Just remember: JavaScript doesn’t have methods. Or classes. Just objects and functions.See also: What is the rationale for the behavior of the ‘this’ keyword in JavaScript?