首页 > Web开发 > 详细

js确保正确this的几种写法

时间:2017-04-30 13:47:59      阅读:272      评论:0      收藏:0      [点我收藏+]

1.直接用bind调用

this.method.bind(this)

2.构造函数中用bind定义

class Foo{
    constructor(){
        this.method = this.method.bind(this);
    }
}

3.用箭头函数定义或调用

//定义
class Foo{
    constructor(){
        //定义1
        this.method1 = () => { this.xxx = b; }
    }
    //定义2
    method2: () => { this.xx = a; }
}

//调用
this.someThingAsync()
  .then(() => {
    this.method()
  })

 

js确保正确this的几种写法

原文:http://www.cnblogs.com/mengff/p/6789193.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!