推荐答案
// www.javascriptcn.com code example
// 箭头函数的基本语法
const add = (a, b) => a + b;
// 箭头函数与普通函数的区别
const obj = {
value: 10,
regularFunction: function() {
console.log(this.value); // 10
},
arrowFunction: () => {
console.log(this.value); // undefined
}
};
obj.regularFunction();
obj.arrowFunction();本题详细解读
箭头函数的基本语法
箭头函数是 ES6 引入的一种新的函数语法,它提供了一种更简洁的方式来定义函数。箭头函数的基本语法如下:
const functionName = (param1, param2, ..., paramN) => {
// 函数体
};如果函数体只有一行代码,并且是返回一个值,可以省略大括号和 return 关键字:
const add = (a, b) => a + b;
箭头函数与普通函数的区别
this的绑定:- 普通函数中的
this是动态绑定的,取决于函数的调用方式。 - 箭头函数中的
this是词法绑定的,它继承自外层函数的this值。
// www.javascriptcn.com code example const obj = { value: 10, regularFunction: function() { console.log(this.value); // 10 }, arrowFunction: () => { console.log(this.value); // undefined } }; obj.regularFunction(); // 输出 10 obj.arrowFunction(); // 输出 undefined- 普通函数中的
不能作为构造函数:
- 箭头函数不能使用
new关键字来创建实例,因为它没有[[Construct]]内部方法。
const Foo = () => {}; const foo = new Foo(); // TypeError: Foo is not a constructor- 箭头函数不能使用
没有
arguments对象:- 箭头函数没有自己的
arguments对象,它会继承外层函数的arguments对象。
// www.javascriptcn.com code example const regularFunction = function() { console.log(arguments); // [1, 2, 3] }; const arrowFunction = () => { console.log(arguments); // ReferenceError: arguments is not defined }; regularFunction(1, 2, 3); arrowFunction(1, 2, 3);- 箭头函数没有自己的
不能使用
yield关键字:- 箭头函数不能用作生成器函数,因此不能使用
yield关键字。
const generatorFunction = function*() { yield 1; }; const arrowFunction = () => { yield 1; // SyntaxError: Unexpected token 'yield' };- 箭头函数不能用作生成器函数,因此不能使用
使用场景
- 回调函数:箭头函数非常适合用作回调函数,尤其是在需要保持
this绑定的情况下。 - 简洁的函数表达式:当函数体非常简单时,箭头函数可以使代码更加简洁。
const numbers = [1, 2, 3]; const doubled = numbers.map(n => n * 2); console.log(doubled); // [2, 4, 6]