箭头函数不适合定义对象的方法(对象字面量方法、对象原型方法、构造器方法),由于箭头函数没有本身的 this,其内部的 this 指向的是外层做用域的 thisjavascript
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 命令
箭头函数不适合定义结合动态上下文的回调函数(事件绑定函数),由于箭头函数在声明的时候会绑定静态上下文java
const button = document.querySelector('button'); button.addEventListener('click', () => { this.textContent = 'Loading...'; }); // this 并非指向预期的 button 元素,而是 window