箭头函数(Arrow Functions)和普通函数(传统函数)在 JavaScript 中有显著的区别,主要体现在语法、this
的绑定、构造函数行为、参数处理等方面。以下是详细对比:
1. 语法差异
-
普通函数:
function add(a, b) {
return a + b;
}
或函数表达式:
const add = function(a, b) {
return a + b;
};
-
箭头函数(更简洁):
const add = (a, b) => a + b; // 省略 return 和大括号(单行返回)
或:
const add = (a, b) => {
return a + b;
};
2. this
的绑定
- 普通函数:
this
是动态绑定的,取决于函数的调用方式。- 例如:
function sayHello() {
console.log(`Hello, ${this.name}`);
}
const person = { name: "Alice" };
sayHello.call(person); // 输出 "Hello, Alice"(通过 call 显式绑定)
- 箭头函数:
- 没有自己的
this
,继承自外层作用域(词法作用域)。 - 例如:
const person = {
name: "Alice",
sayHello: function() {
setTimeout(() => {
console.log(`Hello, ${this.name}`); // 这里的 this 继承自 sayHello 的 this
}, 100);
},
};
person.sayHello(); // 输出 "Hello, Alice"
- 如果用普通函数,
this
会丢失:const person = {
name: "Alice",
sayHello: function() {
setTimeout(function() {
console.log(`Hello, ${this.name}`); // 这里的 this 是 window/undefined(严格模式)
}, 100);
},
};
person.sayHello(); // 输出 "Hello, undefined" 或报错
- 没有自己的
3. 构造函数
- 普通函数:
- 可以作为构造函数,用
new
调用:function Person(name) {
this.name = name;
}
const alice = new Person("Alice");
- 可以作为构造函数,用
- 箭头函数:
- 不能作为构造函数,用
new
调用会报错:const Person = (name) => {
this.name = name; // 报错:箭头函数不能用作构造函数
};
const alice = new Person("Alice"); // TypeError: Person is not a constructor
- 不能作为构造函数,用
4. arguments
对象
- 普通函数:
- 有
arguments
对象,包含所有传入参数:function sum() {
console.log(arguments); // 类似数组的对象
}
sum(1, 2, 3); // 输出 [1, 2, 3]
- 有
- 箭头函数:
- 没有
arguments
对象,但可以通过剩余参数(...args
)模拟:const sum = (...args) => {
console.log(args); // [1, 2, 3]
};
sum(1, 2, 3);
- 没有
5. prototype
属性
- 普通函数:
- 有
prototype
属性,可用于添加方法:function Person() {}
Person.prototype.sayHello = function() {
console.log("Hello");
};
- 有
- 箭头函数:
- 没有
prototype
属性:const Person = () => {};
console.log(Person.prototype); // undefined
- 没有
6. 适用场景
- 普通函数:
- 需要动态
this
的场景(如对象方法、事件回调)。 - 需要作为构造函数。
- 需要
arguments
对象。
- 需要动态
- 箭头函数:
- 简化回调函数(如
map
、filter
、setTimeout
)。 - 需要固定
this
的场景(如 Vue/React 中的方法)。 - 代码更简洁。
- 简化回调函数(如
总结表
特性 | 普通函数 | 箭头函数 |
---|---|---|
语法 | function() {} | () => {} |
this 绑定 | 动态绑定(取决于调用方式) | 继承自外层作用域(词法作用域) |
构造函数 | 可以(new 调用) | 不可以(报错) |
arguments | 有 | 没有(可用 ...args 替代) |
prototype | 有 | 没有 |
适用场景 | 动态 this 、构造函数 | 简化回调、固定 this |
选择建议
- 如果需要动态
this
或构造函数,用普通函数。 - 如果需要简洁语法或固定
this
,用箭头函数。 - 在 Vue/React 中,方法通常用箭头函数或绑定
this
,避免this
丢失问题。