箭头函数

1.ES6的做箭头函数书写方式:安全

var foo = a => {
  console.log( a );
};
foo( 2 ); // 2

这里称做“胖箭头”,一般被看成function 关键字的简写。

2.箭头函数有重要的做用(解决this做用域问题),比较下面函数:闭包

var obj = {
    id: "a",
    cool: function coolFn() {
        console.log( this.id );
    }
};
var id = "b"
obj.cool(); // a
setTimeout( obj.cool, 100 ); // b

问题在于cool() 函数丢失了同this 之间的绑定。(最好的解决方法也是最经常使用的解决方法是var self = this)
以下:

var obj = {
    count: 0,
    cool: function coolFn() {
        var self = this;
        if (self.count < 1) {
            setTimeout( function timer(){
                self.count++;
                console.log( "a" );
            }, 100 );
        }
    }
};
obj.cool(); // a
(self 只是一个能够经过词法做用域和闭包进行引用的标识符,不关心this 绑定的过程当中发生了什么。)


ES6 中的箭头函数引入了一个叫做this 词法的行为:

var obj = {
count: 0,
    cool: function coolFn() {
        if (this.count < 1) {
            setTimeout( () => { 
                this.count++;
                console.log( "a" );
            }, 100 );
        }
    }
};
obj.cool(); // a

总结:函数

简单来讲,箭头函数在涉及this 绑定时的行为和普通函数的行为彻底不一致。它放弃了全部普通this 绑定的规则,取而代之的是用当前的词法做用域覆盖了this 原本的值。所以,这个代码片断中的箭头函数并不是是以某种不可预测的方式同所属的this 进行了解绑定,而只是“继承”了cool() 函数的this 绑定(所以调用它并不会出错)。箭头函数的绑定没法被修改。(new 也不行! ) this

解决的另外一个办法:bind();code

var obj = {
count: 0,
    cool: function coolFn() {
        if (this.count < 1) {
            setTimeout( function timer(){
                this.count++; // this 是安全的, 由于bind(..)
                console.log( "a" );
            }.bind( this ), 100 ); 
        }
    }
};
obj.cool();//a

最后:不管你是喜欢箭头函数中this 词法的新行为模式,仍是喜欢更靠得住的bind(),都须要注意箭头函数不单单意味着能够少写代码。它们之间有意为之的不一样行为须要咱们理解和掌握,才能正确地使用它们。继承

相关文章
相关标签/搜索