Let see code first
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()());
the result is "The Window";
I want to know what happend in every step.
I think this is point to the object which call this function; right?
But why in this case this is window
The second function invocation doesn’t take place from the context of an object, but rather from the function returned from the first invocation.
Because there’s no object context, the
thisvalue becomes the defaultwindowjust like any other function.If we instead assigned the returned function to
object, then invoked it from that context,thiswould then be a reference toobject.Same exact function, but now it’s being invoked from as a property of
object, which implicitly sets itsthisvalue toobject.The rules of
thisare really pretty simple and easy to understand, but may not be what you’d expect at first.The
thisvalue is very dynamic, and is based entirely on how a function is invoked.So you can see that the default is
windowwhen the function is invoked without any sort of connection to another object.But when we call the function as a property of an object,
thissuddenly refers to that object.Or we can use
.call,.applyor.bindto manually set thethisvalue of the function call.