什么时候不该用箭头函数?这五种情况要注意

摘要:ES6 引入箭头函数后,很多开发者喜欢上了它简洁的写法。箭头函数用起来方便,还能避免一些 this 指向问题。但并不是所有地方都适合用箭头函数。有时候用了反而会出错,特别是下面这五种情况。

ES6 引入箭头函数后,很多开发者喜欢上了它简洁的写法。箭头函数用起来方便,还能避免一些 this 指向问题。但并不是所有地方都适合用箭头函数。有时候用了反而会出错,特别是下面这五种情况。

简单来说,箭头函数和普通函数最大的区别在于 this 的指向:

  • 普通函数的 this 是谁调用就指向谁

  • 箭头函数的 this 是定义时就固定了,不会改变

理解了这一点,你就知道为什么下面这些场景必须用普通函数了。


1. 对象中的方法

当我们给对象定义方法时,通常希望方法内部的 this 指向这个对象本身,这样才能访问对象的其他属性。

错误写法(用箭头函数):

const person = {
  name: "小明",
  introduce: () => {
    console.log(`我是${this.name}`); // 这里 this 不是 person
  }
};
person.introduce(); // 输出:我是undefined

正确写法(用普通函数):

const person = {
  name: "小明",
  introduce: function() {
    console.log(`我是${this.name}`);
  }
};
person.introduce(); // 输出:我是小明

也可以用 ES6 的方法简写:

const person = {
  name: "小明",
  introduce() {
    console.log(`我是${this.name}`);
  }
};


2. 事件处理函数

给 DOM 元素添加事件监听时,我们经常需要操作触发事件的元素本身。普通函数会自动把 this 绑定到当前元素上。

错误写法(用箭头函数):

const button = document.getElementById("myButton");
button.addEventListener("click", () => {
  this.classList.add("active"); // 这里 this 不是按钮元素
});

正确写法(用普通函数):

const button = document.getElementById("myButton");
button.addEventListener("click", function() {
  this.classList.add("active"); // this 就是被点击的按钮
});


3. 构造函数

箭头函数不能用作构造函数,尝试用 new 调用会直接报错。

错误写法:

const Person = (name) => {
  this.name = name; // 这里会报错
};
const p = new Person("小明"); // 报错:Person is not a constructor

正确写法(用普通函数):

function Person(name) {
  this.name = name;
}
const p = new Person("小明");
console.log(p.name); // 输出:小明

也可以用 class 语法:

class Person {
  constructor(name) {
    this.name = name;
  }
}


4. 原型方法

在原型上定义方法时,也需要让 this 指向实例对象。

错误写法:

function Person(name) {
  this.name = name;
}
Person.prototype.sayName = () => {
  console.log(this.name); // this 不是实例
};
const p = new Person("小明");
p.sayName(); // 输出:undefined

正确写法:

function Person(name) {
  this.name = name;
}
Person.prototype.sayName = function() {
  console.log(this.name); // this 指向实例
};
const p = new Person("小明");
p.sayName(); // 输出:小明


5. 需要使用 arguments 对象的函数

箭头函数没有自己的 arguments 对象,如果需要使用 arguments,必须用普通函数。

错误写法:

const func = () => {
  console.log(arguments); // 报错:arguments is not defined
};
func(1, 2, 3);

正确写法:

function func() {
  console.log(arguments); // 正常输出参数列表
}
func(1, 2, 3);

不过现在更推荐使用剩余参数语法,箭头函数也能用:

const func = (...args) => {
  console.log(args); // 输出:[1, 2, 3]
};
func(1, 2, 3);


那么什么时候该用箭头函数?

箭头函数最适合用在需要保持 this 指向不变的场景,比如回调函数:

const counter = {
  count: 0,
  start() {
    setInterval(() => {
      this.count++; // 这里的 this 指向 counter
      console.log(this.count);
    }, 1000);
  }
};
counter.start();

在数组方法中也很方便:

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);


总结一下:箭头函数很好用,但不能滥用。在需要动态 this 的场景下,还是得用普通函数。掌握两者的区别,才能写出更可靠的代码。


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_12911