最近读到了一篇介绍js中this的四种使用场景的文章,感觉总结的很好,所以我认真读了读,并且动手实践了其中的demo,与大家共享。原文链接:
https://github.com/alsotang/n...
遇到this,一直要记得这句:函数执行时,this总是指向调用该函数的对象(即:判断this所在的函数属于谁)。
1、函数有所属对象,则指向所属对象
-
var myObject={
-
value:100
-
};
-
myObject.getValue=function(){
-
console.log(this.value);
-
console.log(this);
-
return this.value;
-
}
-
console.log(myObject.getValue());
这里的getValue属于对象myObject,所以this就指向myObject,执行结果如下:
2、函数没有所属对象时,就指向全局对象(window或global)
-
var myObject={
-
value:100
-
};
-
myObject.getValue=function(){
-
var foo=function(){
-
console.log(this.value);
-
console.log(this);
-
}
-
foo();
-
return this.value;
-
}
-
console.log(myObject.getValue());
在这里,foo属于全局对象,所以foo函数打印的this.value为undefined。
写到这里,我又想起setTimeout和setInterval方法也是属于全局对象的,所以在这两个函数体内this是指向全局的,所以也是这种情况,如下:
-
var myObject={
-
value:100
-
};
-
myObject.getValue=function(){
-
setTimeout(function(){
-
console.log(this.value);
-
console.log(this);
-
},0);
-
return this.value;
-
}
-
console.log(myObject.getValue());
执行结果如下:
所以,如果要得到想要的结果,就要这样写了吧:
-
myObject.getValue=function(){
-
let self=this;//用一个self保存当前的实例对象,即myObject
-
setTimeout(function(){
-
console.log(self.value);
-
console.log(self);
-
},0);
-
return this.value;
-
}
-
console.log(myObject.getValue());
结果如下:
这又让我想起来了es6中箭头函数的妙用了(这个this绑定的是定义时所在的作用域,而不是运行时所在的作用域;箭头函数其实没有自己的this,所以箭头函数内部的this就是外部的this)(可详看es6教程:http://es6.ruanyifeng.com/#do...箭头函数),如下:
-
var myObject={
-
value:100
-
};
-
myObject.getValue=function(){
-
// let self=this;//因为用了箭头函数,所以这句不需要了
-
setTimeout(()=>{
-
console.log(this.value);
-
console.log(this);
-
},0);
-
return this.value;
-
}
-
console.log(myObject.getValue());
执行结果同上:
3、使用构造器new一个对象时,this就指向新对象:
-
var oneObject=function(){
-
this.value=100;
-
};
-
var myObj=new oneObject();
-
console.log(myObj.value);
这里的this就指向了new出来的新对象myObj,执行结果如下:
4、apply,call,bind改变了this的指向
-
var myObject={
-
value:100
-
}
-
var foo=function(){
-
console.log(this);
-
console.log(this.value);
-
console.log("...............");
-
}
-
foo();
-
foo.apply(myObject);
-
foo.call(myObject);
-
var newFoo=foo.bind(myObject);
-
newFoo();
foo本来指向全局对象window,但是call,apply和bind将this绑定到了myObject上,所以,foo里面的this就指向了myObject。执行代码如下: