首页 > IT职业 > IT图书 > 箭头函数适用场景及需要注意的地方
箭头函数不适合定义对象的方法(对象字面量方法、对象原型方法、构造器方法),因为箭头函数没有自己的 this,其内部的 this 指向的是外层作用域的 this
const json = {
bar: 1,
fn: () => console.log(this.bar)
};
json.fn(); //-> undefined
// this 并不是指向 json 这个对象,而是再往上到达全局作用域 function Foo() {
this.bar = 1;
}
Foo.prototype.fn = () => console.log(this.foo);
const foo = new Foo();
foo.fn(); //-> undefined
// this 并不是指向 Foo,根据变量查找规则,回溯到了全局作用域 const Message = (text) => {
this.text = text;
};
var helloMessage = new Message('Hello World!');
console.log(helloMessage.text); //-> Message is not a constructor
// 不可以当作构造函数,也就是说,不可以使用 new 命令 箭头函数不适合定义结合动态上下文的回调函数(事件绑定函数),因为箭头函数在声明的时候会绑定静态上下文
const button = document.querySelector('button');
button.addEventListener('click', () => {
this.textContent = 'Loading...';
});
// this 并不是指向预期的 button 元素,而是 window 来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1795/viewspace-2808103/ ,如需转载,请注明出处,否则将追究法律责任。