This in JavaScript is always confusing and should be one of JS's well-known pits. Personally also feel JS in this is not a good design, due to this late binding feature, it can be global object, current object, or ... Some people even use this because of the big hole. In fact, if you fully mastered the working principle of this, nature will not go into these pits. Let's look at what this difference points to in these situations:
1. This in the global Code
Alert (This)//window
This in the global scope will point to the global object, even window in the browser.
2. As a simple function call
Functionfoocoder (x) {
this.x = x;
}
Foocoder (2);
alert (x);//global variable x value 2
Here this points to the Global object, window. In strict mode, it is undefined.
3. Method calls as objects
VarName = "clever coder";
Varperson = {
name: "Foocoder",
hello:function (sth) {
Console.log (this.name + "says" + sth);
}
}
Person.hello ("Hello World");
Output foocoder says Hello world. This points to the person object, which is the current object.
4. As a constructor
Newfoocoder ();
This point inside the function points to the newly created object.
5. Internal function
VarName = "clever coder";
Varperson = {
name: ' Foocoder ',
hello:function (sth) {
Varsayhello = function (sth) {
Console.log ( THIS.name + "says" + sth);
SayHello (STH);
}
Person.hello ("Hello World");//clever coder says Hello World
In an intrinsic function, this is not bound to the outer function object as expected, but is bound to the global object. This is generally considered a design error for JavaScript language, because no one wants this to point to the global object in the internal function. The general approach is to save this as a variable, which is generally agreed to that or self:
VarName = "clever coder";
Varperson = {
name: "Foocoder",
hello:function (sth) {
varthat = this;
Varsayhello = function (sth) {
Console.log (that.name + "says" + sth);
SayHello (STH);
}
6. Use call and apply to set this
Person.hello.call (Person, "the World");
Apply and call are similar, except that the subsequent arguments are passed through an array instead of being passed in separately. The method definition of both:
Call (Thisarg [, ARG1,ARG2, ...]); Parameter list, arg1,arg2,...apply (Thisarg [, Argarray]); Parameter array, Argarray
Both are used to bind a function to a specific object, and naturally this will be explicitly set to the first argument.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/