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?
In JavaScript, this
represents 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). For MyFunc
, this references the new object being created; but for innerFunc
, it references the global object, since no context is specified when innerFunc
is called.
This tends to trip up those used to Java or similar OO languages, where this
almost 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.
As a sidenote, "this" isn't necessarily referencing the actual function all the time, since you can invoke a function with a "forced" this-reference, think about an event-handler, in which this will refer to the actual element that fired the event.
using
yourFunction.apply(thisReference, arguments)
you can invoke it where "this" will point to whatever you pass on as first argument.
Just do the following:
var MyFunc = function(){
var self = this;
alert(self);
var innerFunc = function(){
alert(self);
}
innerFunc();
};
new MyFunc();
This way self will always mean this, irrespective of where you're calling it from, which is usually what you want.
At first glance I'd say it's because the outer 'this' is in reference to MyFunc and the inner 'this' is in reference to innerFunc.
However, Javascript isn't something I have any particular expertise in.