Today, a friend said that he encountered the following code and asked me to explain the reason
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this. name;
};
}
};
alert(object.getNameFunc()()); The reason is that this of js is determined dynamically, and how you call it There is a direct relationship.
Simply put, if you use the "object.function name" method when calling a function, then this is the object before the . (dot), otherwise it is window.
For example, when you call object.getNameFunc(), this in the getNameFunc function body is the object you just declared. If you write
var func = object.getNameFunc;
func();
At this time, this in the getNameFunc function body is window, although the difference in calling the same function determines the difference in this.
Similarly, object.getNameFunc() returns a function reference. Adding parentheses allows the function to be executed. In fact, it is equivalent to the following code
var func = object.getNameFunc( );
alert( func() );
There is no "object." form before the function, so when executing the function, this is window, and the result is obvious.
I will write an article about js this in the future. Everyone is welcome to follow my CSDN blog tt361.