箭头函数和普通函数确实有几个区别,主要包括 this 绑定、语法、构造函数和 arguments 对象。
1. this 绑定
- 普通函数:
this的值是在函数被调用时决定的,这也即所谓的动态this绑定。
const obj = {
regularFunction: function() {
console.log(this); // this 指向 obj
}
};
obj.regularFunction();
- 箭头函数:
this是在函数定义时确定的,继承自其定义环境的父this。
const obj = {
arrowFunction: () => {
console.log(this); // this 指向全局对象或 undefined(严格模式下)
}
};
obj.arrowFunction();
const obj2 = {
method() {
const inner = () => {
console.log(this); // this 指向 obj2
};
inner();
}
};
obj2.method();
2. 语法简洁
- 普通函数:
function add(a, b) {
return a + b;
}
- 箭头函数:
const add = (a, b) => a + b;
3. 构造函数
- 普通函数可以用作构造函数,可以通过
new关键字实例化:
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john.name); // John
- 箭头函数不能作为构造函数使用:
const Person = (name) => {
this.name = name;
};
// const john = new Person('John'); // TypeError: Person is not a constructor
4. arguments 对象
- 普通函数会创建
arguments对象,包含传入到函数中的所有参数:
function showArgs() {
console.log(arguments);
}
showArgs(1, 2, 3); // Arguments [1, 2, 3]
- 箭头函数没有
arguments对象,但可以使用 rest 参数语法来达到类似目的:
const showArgs = (...args) => {
console.log(args);
};
showArgs(1, 2, 3); // [1, 2, 3]
通过以上例子可以看到,箭头函数在某些场景下提供了更具优势的简洁和明确绑定的特性,但也由于其特性在某些场景下不适合用作一般函数的替代品,例如需要动态 this、arguments 对象或用作构造函数时。选择合适的函数形式需要考虑这些差异。