This is a keyword of JavaScript, and the value of this will change as the function is used in different situations. But there is always a principle that this refers to the object that invokes the function.
1. This in the global Code
alert (this);//window
This points to the global object.
2. As a simple function call
function Foocoder (x) {
this.x = x;
}
Foocoder (2);
alert (x);//global variable x value is 2
This points to the global object, which is window. In strict mode, it is undefined.
3. Method calls as objects
var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
Console.log (this.name + "says" + sth);
}
}
Person.hello ("Hello World"),//foocoder says Hello World
This points to the person object, which is the current object.
4. As a constructor
New Foocoder ();
This points to the newly created object.
5. Intrinsic functions
var name = "Clever coder";
var person = {
Name: "Foocoder",
Hello:function (STH) {
var SayHello = 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.
6. Use call and apply to set this
Person.hello.call (Person, "world");//apply and call are similar, except that the arguments are passed in an array, not separately.
Both are used to bind a function to a specific object, and this will naturally be set to the first parameter explicitly.
JS in the This keyword