箭头函数(Arrow Function) 是一种简化的 JavaScript
函数表达式,它的语法中省略了传统函数定义中的 function
关键字。
javascriptconst add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // 输出: 5
javascriptconst add = (a, b) => {
return a + b;
};
console.log(add(2, 3)); // 输出: 5
function
关键字,箭头 =>
取而代之。javascriptconst func = (参数1, 参数2, ...) => {
// 函数体
return 结果;
};
简化规则
只有一个参数时,可以省略参数的括号 ()
:
javascriptconst square = x => x * x;
console.log(square(5)); // 输出: 25
只有一个返回值时,可以省略大括号 {}
和 return
关键字,直接返回值:
javascriptconst add = (a, b) => a + b;
console.log(add(2, 3)); // 输出: 5
没有参数时
必须保留空的括号 ()
:
javascriptconst greet = () => "Hello!";
console.log(greet()); // 输出: Hello!
不绑定 this
this
,它的 this
是继承自定义它的上下文环境。this
指向的场景(如事件回调、定时器等)。示例:传统函数中的问题
javascriptfunction Person() {
this.age = 0;
setInterval(function () {
this.age++;
console.log(this.age); // `this` 指向了全局对象,而不是 Person
}, 1000);
}
new Person(); // 输出: NaN
解决方法:箭头函数
javascriptfunction Person() {
this.age = 0;
setInterval(() => {
this.age++; // `this` 指向 Person 实例
console.log(this.age);
}, 1000);
}
new Person(); // 正确输出: 1, 2, 3...
不能用作构造函数
this
,因此不能用作构造函数,不能使用 new
操作符。没有 arguments
对象
arguments
,如果需要,可以通过 ...rest
参数获取所有参数。示例:传统函数
javascriptfunction printArgs() {
console.log(arguments); // 输出: [1, 2, 3]
}
printArgs(1, 2, 3);
箭头函数
javascriptconst printArgs = (...args) => {
console.log(args); // 输出: [1, 2, 3]
};
printArgs(1, 2, 3);
不能用作 yield
的生成器函数
yield
关键字。箭头函数是一种简化的函数表达式,相比传统函数:
function
关键字。=>
表示函数体。this
的行为,是现代 JavaScript 中推荐的函数表达形式。本文作者:空白格
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!