箭头函数的语法更简洁,不需要 function
关键字,并且如果只有一个参数时可以省略括号。如果函数体只有一个表达式,还可以省略大括号和 return
关键字。
// 普通函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => a + b;
// 无参数箭头函数
const greet = () => 'Hello';
// 单参数箭头函数
const square = x => x * x;
this
绑定箭头函数不会创建自己的 this
,它会捕获其所在上下文的 this
值,即所谓的“词法绑定” (lexical binding
)。而普通函数会根据调用方式动态绑定 this
。
// 普通函数
function Person() {
this.age = 0;
setInterval(function growUp() {
this.age++; // this 指向全局对象或 undefined(严格模式下)
}, 1000);
}
// 使用箭头函数
function Person() {
this.age = 0;
setInterval(() => {
this.age++; // this 指向 Person 实例
}, 1000);
}
const p = new Person();
arguments
对象箭头函数没有 arguments
对象。如果需要使用 arguments
,可以使用 rest 参数 ...args
来代替。
// 普通函数
function sum() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
// 箭头函数
const sum = (...args) => {
return args.reduce((total, arg) => total + arg, 0);
};
箭头函数不能用作构造函数,不能使用 new
关键字实例化对象。
function Person(name) {
this.name = name;
}
const john = new Person('John'); // 正常
const PersonArrow = (name) => {
this.name = name;
};
const jane = new PersonArrow('Jane'); // TypeError: PersonArrow is not a constructor
yield
关键字箭头函数不能用作生成器函数,不能使用 yield
关键字。
// 普通生成器函数
function* generatorFunction() {
yield 1;
yield 2;
yield 3;
}
// 箭头函数不能用作生成器
const generatorFunction = () => {
yield 1; // SyntaxError: Unexpected strict mode reserved word
};
this
绑定需求的函数,如数组方法中的回调函数(如 map
、filter
、reduce
)和事件处理函数。this
绑定、arguments
对象或构造函数的场景。下面的例子展示了箭头函数和普通函数在 this
绑定上的区别:
const obj = {
value: 42,
regularFunction: function() {
console.log(this.value); // this 指向 obj,输出 42
},
arrowFunction: () => {
console.log(this.value); // this 指向全局对象,输出 undefined
}
};
obj.regularFunction();
obj.arrowFunction();
箭头函数和普通函数在语法、this
绑定、arguments
对象、构造函数和生成器函数等方面有显著区别。理解这些区别有助于在合适的场景中选择合适的函数类型,从而编写更简洁、高效的代码。