A function in JavaScript can be executed as a normal function or as a method of an object, which is the main reason for the richness of this meaning.
var name= "The window" var object={ Name: "My object", getnamefunc:function () { return function () { return this.name;}} }
Why is this output the window and the following output is my Object?
var name= "The window" var object={ Name: "My object", getnamefunc:function () { var = this; return function () { return that.name;}} }
Call Code alert (Object.getnamefunc () ());
JavaScript is a dynamic (or dynamic type) language, and the This keyword is executed to determine who it is. So this always points to the caller, that is, a reference to the ' Call object ' person.
The first part returns a function through the code: OBJECT.GETNAMEFUNC () call. This is a returned function, which is not a property or method of object, at which time the caller is window. So the output is the Window
The second part returns when the function Object.getnamefunc () is executed:
function ()
{
return that.name;
}
At this time the that=this. And this points to object, so that's point to object. No matter how many times you execute, he is a reference to object, so output my object
Because of the nature of its run-time bindings, this meaning in JavaScript is much richer, and it can be a global object, the current object, or any object, depending on how the function is called.
The invocation of a function in JavaScript has several ways: as an object method call, as a function call, as a constructor call, and with an apply or call invocation .
RELATED links:
this:http://www.ibm.com/developerworks/cn/web/1207_wangqf_jsthis/in layman's JavaScript
The This in JavaScript