看了阮一峰的this讲解,下面是个人理解:app
总结来讲 this指向 调用this所在方法 的对象;函数
例子1this
function test(){
this.x = 1;
console.log(x);
}
test();//1
由于调用test()方法是window即全局,因此这时的this指向全局code
为了证实的确是改变了全局变量看下面的例子,在外面给x赋值了2,可是在test里面仍是会被改变
例子2对象
var x = 2;
function test(){
this.x = 1;
console.log(x);
}
test();//1
function test(){
this.x = 1;
}
x = 2;
var a = new test();
console.log(a.x);//1
console.log(x);//2
能够看出第一个的x只是指向a这个对象,而第二个x是指向Window做为全局变量继承
function test(){
console.log(this.x);
}
var a = {};
a.func =test;
a.x = 2;
a.func();//2
这里能够看出来test方法是被a对象调用,因此this指向a,因此this.x 实际上是 a.x ,因此是2io
var x = 1;
function test(){
console.log(this.x);
}
var a = {};
a.x = 2;
a.func = test;
a.func.apply();//1
a.func.apply()表明是window继承a的func属性即test方法,因此执行了test ,这时这里的this指向是window,由于是window调用的,因此是1console