码迷,mamicode.com
首页 > Web开发 > 详细

js确保正确this的几种写法

时间:2017-04-30 14:07:40      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:pre   定义   函数   构造函数   cto   struct   color   code   class   

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的几种写法

标签:pre   定义   函数   构造函数   cto   struct   color   code   class   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!