箭头函数没有自己的this
,导致内部的this
就是外层代码块的this
。正是因为它没有this
,所以也就不能用作构造函数。
一个示例:
// ES6
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log('id:', _this.id);
}, 100);
}
除了没有this
,以下三个变量在箭头函数之中也是不存在的,指向外层函数的对应变量:arguments
、super
、new.target
。
另外,由于箭头函数没有自己的this
,所以当然也就不能用call()
、apply()
、bind()
这些方法去改变this
的指向。
(function() {
return [
(() => this.x).bind({ x: 'inner' })()
];
}).call({ x: 'outer' });
// ['outer']
不适用的场合
1、定义对象的方法,且该方法内部包括this
const cat = {
lives: 9,
jumps: () => {
this.lives--;
}
}
此时,this
指向全局对象,而不使用箭头函数的时候this
指向cat
对象。
2、需要动态this
的时候
var button = document.getElementById('press');
button.addEventListener('click', () => {
this.classList.toggle('on');
});
这个this
也指向全局对象,而普通函数则指向被点击的按钮。