5种应该避免使用箭头函数的情况

  • 2019 年 12 月 30 日
  • 筆記

摘要: 箭头函数也有可能会有BUG…

Fundebug经授权转载,版权归原作者所有。

1. 避免在定义对象方法时使用

箭头函数虽然因语法简练受人追捧。但由于没有 this 会导致在一些情况下出现预想不到的意外情况。

比如在对象中定义一个方法:

this.food = "banana";    let obj = {      food: "strawberry",      log() {          console.log(this.food);      }  };    obj.log(); // 打印"strawberry"

看起来很完美调用这个方法能够按照预期,获得对象的 food 属性

但如果将其改为箭头函数:

this.food = "banana";    let obj = {      food: "strawberry",      log: () => {          console.log(this.food);      }  };    obj.log(); // 打印"banana"

由于箭头函数自身没有 this 会导致自动继承外层的 this 导致打印出的变量出错,这个 bug 有点坑。。

因此不要在对象方法中使用箭头函数。

2. 避免在 prototype 上使用

因为没有 this 导致 this 指向错误,所以在定义 prototype 方法上一定记得不要使用箭头函数

this.name = "oli"; // this 从外层基础    function Person(name) {      this.name = name;  }    Person.prototype.log = () => {      console.log(this.name);  };    let p = new Person();    p.log(); // 打印"oli"

3. 避免在需要 arguments 上使用

因为箭头函数没有 arguments 因此如果外层是另外一个函数,那么 arguments 是这个外层函数的

function foo() {      return (...argv) => {          console.log(...arguments); // 打印[1, 2, 3],箭头函数并没有arguments需要从外部函数获取          console.log(...argv); // 打印[1, 2, 3, 4]      };  }    foo([1, 2, 3])([1, 2, 3, 4]);

当然可以使用 rest 操作符获取对应的参数

4. 避免在动态上下文中的回调函数里使用

如果你需要你的上下文是可变的,动态的,那么不要使用箭头函数

比如在一个页面中,我们需要为每一个 p 元素增加一个事件处理函数,那么:

document.querySelectorAll('p').forEach(elem => {      elem.addEventListener('click', () => {          console.log(this.innerText.length) // 这个时候 this 指向 window,因此会报错      })  })

改为普通函数才可以正确访问到预期的 this:

document.querySelectorAll('p').forEach(elem => {      elem.addEventListener('click', function() {          console.log(this.innerText.length) // 这个时候 this 指向 elem      })  })

5. 避免在需要 caller 的时候使用

因 caller 早已不再是推荐的标准,应该在任何时候都避免使用 caller 这里就不多说了

其他情况下尤其是 map reduce forEach 等并没有什么复杂的逻辑的时候使用箭头函数能够增加阅读体验,想必是极好的。

版权声明

转载时请注明作者 Fundebug以及本文地址: https://blog.fundebug.com/2019/05/07/5-cases-not-use-arrow-function/

您的用户遇到BUG了吗?

体验Demo 免费使用

.copyright *{box-sizing:border-box}