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

66 阅读1分钟
  • 箭头函数没有prototype(原型),所以箭头函数没有本身this;
  • 箭头函数的this指向在定义的时候继承自外层第一个普通函数的this。
  • 箭头函数的指向不能直接修改。

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

例如:

var name = "123";
let obj = {
    name:"456",
    log:()=>{
     console.log(this.name)
    }
}
obj.log();  //打印出来的是 123

箭头函数自身没有 this会导致自动继承外层的 this。

2. 避免在定义原型时使用

function Foo(type) {
  this.type = type;
}

Foo.prototype.setType = () => {
  return this.type;  //这里的this指向window
};

const foo = new Foo("data");
console.log(foo.setType());  // undefined

3. 避免在需要arguments上使用

4. 需要使用命名函数时(箭头函数是匿名的)

5. 需要函数提升时(箭头函数只能写成表达式形式)