Today, a friend told me that he met the following code and asked me to explain the reason.
Copy codeThe Code is as follows:
Var name = "The Window ";
Var object = {
Name: "My Object ",
GetNameFunc: function (){
Return function (){
Return this. name;
};
}
};
Alert (object. getNameFunc (); the reason is that js's this is dynamically determined and has a direct relationship with your call method.
To put it simply, if you use the "object. function name" method when calling a function, this is the object before this. (vertex); otherwise, it is the window.
For example, when you call object. getNameFunc (), this in the getNameFunc function is the object you just declared. If you write
Copy codeThe Code is as follows:
Var func = object. getNameFunc;
Func ();
At this time, this in the getNameFunc function is window, although it is different from the call method of the same function, this is different.
In the same way, object. getNameFunc () returns a function reference. Adding a bracket is used to execute the function. Actually, it is equivalent to the following code:
Copy codeThe Code is as follows:
Var func = object. getNameFunc ();
Alert (func ());
There is no "object." form before the function, so when the function is executed, this is a window, and the result is very obvious.
I will write an article about js this in the future. You are welcome to pay attention to my CSDN blog tt361.