3. 箭头函数
优先使用箭头函数,不过以下几种情况避免使用:
1. 使用箭头函数定义对象的方法
- // 例子 3-1
- // bad
- let foo = {
- value: 1,
- getValue: () => console.log(this.value)
- }
- foo.getValue(); // undefined
2. 定义原型方法
- // 例子 3-2
- // bad
- function Foo() {
- this.value = 1
- }
- Foo.prototype.getValue = () => console.log(this.value)
- let foo = new Foo()
- foo.getValue(); // undefined
3. 作为事件的回调函数
- // 例子 3-3
- // bad
- const button = document.getElementById('myButton');
- button.addEventListener('click', () => {
- console.log(this === window); // => true
- this.innerHTML = 'Clicked button';
- });