js确保正确this的几种写法

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()
  })

 

posted @ 2017-04-30 12:13  全玉  阅读(663)  评论(0编辑  收藏  举报