This is a keyword in the JavaScript language.
It represents an internal object that is automatically generated when the function is run, and can only be used inside a function. Like what
function test () {
this.x = 1;
}
The value of this will change as the function is used differently. But there is a general principle, and that is this refers to the object that invokes the function.
Here are four different scenarios for a detailed discussion of this usage.
Case one: pure function call
This is the most common use of a function, which is a global call, so this represents the globally object.
Take a look at the code below and it runs 1.
function test () {
this.x = 1;
alert (this.x);
}
Test (); 1
To prove that this is the global object, I make some changes to the code:
var x = 1;
function test () {
alert (this.x);
}
Test (); 1
The results of the operation are still 1. Change again:
var x = 1;
function test () {
this.x = 0;
}
Test ();
alert (x); 0
Case two: Call as an object method
A function can also be invoked as a method of an object, at which point this is the ancestor object.
function test () {
alert (this.x);
}
var o = {};
o.x = 1;
O.M = test;
O.M (); 1
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/