This article through a piece of code and you simply say JS in the use of this and related issues, interested friends can refer to ha, I hope to help you
Today, a friend said that the following code, let me help explain why
Copy Code code 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 this is dynamically determined by JS, which is directly related to the way you call it.
Simply put, if you call a function by using the "object. Function Name" method, then this is this. (dot) before the object, otherwise it is window.
For example, when you call Object.getnamefunc () the This in the body of the Getnamefunc function is the object just declared. If you write
Copy Code code as follows:
var func = Object.getnamefunc;
Func ();
This is the window in the body of the Getnamefunc function, although the difference of this is determined by the way that the same function is invoked.
In the same way, Object.getnamefunc () returns a function reference, with a bracket that lets the function execute. Actually corresponds to the following code
Copy Code code as follows:
var func = Object.getnamefunc ();
Alert (func ());
There is no "object" before the function. This form, so this is window when the function is executed, and the result is obvious.
Later I will write an article about JS this, welcome everyone to pay attention to my CSDN blog tt361.