箭头函数
js
var foo = a => {
console.log( a );
};
foo( 2 ); // 2
箭头函数修复了this指向的一个问题。问题代码如下
js
var obj = {
id: "awesome",
cool: function coolFn() {
console.log(this.id);
}
};
var id = "not awesome"
obj.cool(); // 酷
setTimeout(obj.cool, 100); // 不酷 这里的this指向window,没有指向obj
旧的修复方式1,通过闭包来解决
- 使用self变量引用声明时指向的this
js
var obj = {
count: 0,
cool: function coolFn() {
var self = this;
if (self.count < 1) {
setTimeout(function timer() {
self.count++;
console.log("awesome?");
}, 100);
}
}
};
obj.cool(); // awesome?
箭头函数也可以修复这个this绑定问题
- 箭头函数在涉及 this 绑定时的行为和普通函数的行为完全不一致
- 是用当前的词法作用域覆盖了 this 本来的值
- 这个代码片段中的箭头函数"继承"了 cool() 函数的 this 绑定(因此调用它并不会出错)。
js
var obj = {
count: 0,
cool: function coolFn() {
if (this.count < 1) {
setTimeout(() => { // 箭头函数是什么鬼东西?
this.count++;
console.log("awesome?");
}, 100);
}
}
};
obj.cool(); // awesome?
还有一种旧的修复方式,就是使用函数的bind方法,进行this绑定
js
var obj = {
count: 0,
cool: function coolFn() {
if (this.count < 1) {
setTimeout(function timer() {
this.count++; // this 是安全的
// 因为 bind(..)
console.log("more awesome");
}.bind(this), 100); // look, bind()!
}
}
};
obj.cool(); // more awesome