js中this的四种使用场景

最近读到了一篇介绍js中this的四种使用场景的文章,感觉总结的很好,所以我认真读了读,并且动手实践了其中的demo,与大家共享。原文链接:
https://github.com/alsotang/n...
遇到this,一直要记得这句:函数执行时,this总是指向调用该函数的对象(即:判断this所在的函数属于谁)。

1、函数有所属对象,则指向所属对象

 
  1. var myObject={

  2. value:100

  3. };

  4. myObject.getValue=function(){

  5. console.log(this.value);

  6. console.log(this);

  7. return this.value;

  8. }

  9. console.log(myObject.getValue());

这里的getValue属于对象myObject,所以this就指向myObject,执行结果如下: 
clipboard.png

2、函数没有所属对象时,就指向全局对象(window或global)

 
  1. var myObject={

  2. value:100

  3. };

  4. myObject.getValue=function(){

  5. var foo=function(){

  6. console.log(this.value);

  7. console.log(this);

  8. }

  9. foo();

  10. return this.value;

  11. }

  12. console.log(myObject.getValue());

在这里,foo属于全局对象,所以foo函数打印的this.value为undefined。
clipboard.png

写到这里,我又想起setTimeout和setInterval方法也是属于全局对象的,所以在这两个函数体内this是指向全局的,所以也是这种情况,如下:

 
  1. var myObject={

  2. value:100

  3. };

  4. myObject.getValue=function(){

  5. setTimeout(function(){

  6. console.log(this.value);

  7. console.log(this);

  8. },0);

  9. return this.value;

  10. }

  11. console.log(myObject.getValue());

执行结果如下:
clipboard.png

所以,如果要得到想要的结果,就要这样写了吧:

 
  1. myObject.getValue=function(){

  2. let self=this;//用一个self保存当前的实例对象,即myObject

  3. setTimeout(function(){

  4. console.log(self.value);

  5. console.log(self);

  6. },0);

  7. return this.value;

  8. }

  9. console.log(myObject.getValue());

结果如下:
clipboard.png

这又让我想起来了es6中箭头函数的妙用了(这个this绑定的是定义时所在的作用域,而不是运行时所在的作用域;箭头函数其实没有自己的this,所以箭头函数内部的this就是外部的this)(可详看es6教程:http://es6.ruanyifeng.com/#do...箭头函数),如下:

 
  1. var myObject={

  2. value:100

  3. };

  4. myObject.getValue=function(){

  5. // let self=this;//因为用了箭头函数,所以这句不需要了

  6. setTimeout(()=>{

  7. console.log(this.value);

  8. console.log(this);

  9. },0);

  10. return this.value;

  11. }

  12. console.log(myObject.getValue());

执行结果同上:
clipboard.png

3、使用构造器new一个对象时,this就指向新对象:

 
  1. var oneObject=function(){

  2. this.value=100;

  3. };

  4. var myObj=new oneObject();

  5. console.log(myObj.value);

这里的this就指向了new出来的新对象myObj,执行结果如下:
clipboard.png

4、apply,call,bind改变了this的指向

 
  1. var myObject={

  2. value:100

  3. }

  4. var foo=function(){

  5. console.log(this);

  6. console.log(this.value);

  7. console.log("...............");

  8. }

  9. foo();

  10. foo.apply(myObject);

  11. foo.call(myObject);

  12. var newFoo=foo.bind(myObject);

  13. newFoo();

foo本来指向全局对象window,但是call,apply和bind将this绑定到了myObject上,所以,foo里面的this就指向了myObject。执行代码如下:
clipboard.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值