3. 箭头函数

优先使用箭头函数,不过以下几种情况避免使用:

1. 使用箭头函数定义对象的方法

  1. // 例子 3-1
  2.  
  3. // bad
  4. let foo = {
  5. value: 1,
  6. getValue: () => console.log(this.value)
  7. }
  8.  
  9. foo.getValue(); // undefined

2. 定义原型方法

  1. // 例子 3-2
  2.  
  3. // bad
  4. function Foo() {
  5. this.value = 1
  6. }
  7.  
  8. Foo.prototype.getValue = () => console.log(this.value)
  9.  
  10. let foo = new Foo()
  11. foo.getValue(); // undefined

3. 作为事件的回调函数

  1. // 例子 3-3
  2.  
  3. // bad
  4. const button = document.getElementById('myButton');
  5. button.addEventListener('click', () => {
  6. console.log(this === window); // => true
  7. this.innerHTML = 'Clicked button';
  8. });