ES6笔记之 arrow function

arrow function 箭头函数,应该是ES6语法中应用最多的地方
长期以来 JavaScript语言的this对象一直是一个令人头痛的问题,在对象方法中使用this,必须小心

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout(function(){
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}

如setTimeout(function(){},1000) 里的function,这里想打印出this.type,却会报错,原因是因为这里的this指向函数的使用者window全局对象

传统的解决办法有两种

第一种是将this传给self,再用self来指代this

   says(say){
       var self = this;
       setTimeout(function(){
           console.log(self.type + ' says ' + say)
       }, 1000)
  }

第二种方法是用bind(this),即

   says(say){
       setTimeout(function(){
           console.log(this.type + ' says ' + say)
       }.bind(this), 1000)
  }
但现在我们有了箭头函数,就不需要这么麻烦了:
 
class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}
 var animal = new Animal()
 animal.says('hi')  //animal says hi

我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。

 

posted @ 2017-07-11 15:14  H5工程师  阅读(173)  评论(0编辑  收藏  举报