this
is a keyword in JavaScript.
function test(){
this.x = 10;
}
in this case this
represents the internal object, only can use in the function.
With the function of different occasions, this
's value will change. But there is a general principle: this
means the object which invoke the function.
Case 1:
pure function call:
This is the most common use of the function, belongs to the global call.
So this
just means of the global object Global.
e.g:
function test(){
this.m = 10;
alert(this.m);
}
test(); // there alert 10
In order to prove this
is a global object:
var m = 10;
function test(){
alert(this.m);
}
test(); // 10
And:
var m = 10;
function test(){
this.m = 0;
}
test();
alert(m); // 10
Case 2:
As the object which calls the function.
function test(){
alert(this.m);
}
var obj = {};
obj.m = 10;
obj.n = test;
obj.n(); // 10
Case 3:
As a constructor
function test(){
this.m = 10;
}
var obj = new test();
alert(obj.m); // 10
In order to show that this
is not a global object in this case:
var m = 10;
function test(){
this.m = 1;
}
var o = new test();
alert(m); //10