JavaScript 箭头函数
箭头函数是ECMAScript 6 (ES6) 引入的一种定义函数的新语法,它为我们提供了一种更简洁的函数表达式写法。除了语法更加简洁外,箭头函数还有一些与传统函数不同的特性,尤其是在处理this
关键字的方式上。
基本语法
让我们首先来看看箭头函数的基本语法:
// 传统函数表达式
const hello = function() {
return "Hello World!";
};
// 箭头函数
const hello = () => {
return "Hello World!";
};
// 如果函数体只有一条返回语句,可以省略大括号和return关键字
const hello = () => "Hello World!";
console.log(hello()); // 输出: Hello World!
箭头函数的语法比传统函数更加简洁,尤其是当函数体只有一条语句时。
参数处理
箭头函数处理参数的方式如下:
// 无参数
const sayHello = () => "Hello";
// 单个参数(可以省略括号,但不推荐)
const double = x => x * 2;
// 或者更清晰的写法
const double = (x) => x * 2;
// 多个参数
const add = (a, b) => a + b;
console.log(sayHello()); // 输出: Hello
console.log(double(4)); // 输出: 8
console.log(add(5, 3)); // 输出: 8
提示
虽然单个参数可以省略括号,但为了代码的一致性和可读性,建议始终使用括号。
箭头函数特性
1. this
值绑定
箭头函数不会创建自己的this
上下文,而是继承父作用域的this
值。这与传统函数不同,传统函数的this
值取决于函数调用的上下文。
const person = {
name: '张三',
// 传统函数
sayNameTimeout1: function() {
setTimeout(function() {
console.log(this.name); // 输出: undefined (this指向window或全局对象)
}, 100);
},
// 箭头函数
sayNameTimeout2: function() {
setTimeout(() => {
console.log(this.name); // 输出: 张三 (this保持指向person对象)
}, 100);
}
};
person.sayNameTimeout1();
person.sayNameTimeout2();
2. 不能作为构造函数
箭头函数不能用作构造函数,不能使用new
关键字调用。
const Person = (name) => {
this.name = name;
};
// 错误!箭头函数不能用作构造函数
// const person = new Person('张三'); // TypeError: Person is not a constructor
3. 没有arguments
对象
箭头函数没有自己的arguments
对象,但可以访问外围函数的arguments
对象。
function outer() {
const inner = () => {
console.log(arguments); // 输出outer函数的arguments
};
inner();
}
outer(1, 2, 3); // 输出: [1, 2, 3]
不过,可以使用剩余参数(rest parameter)来收集所有参数:
const sum = (...args) => {
return args.reduce((total, num) => total + num, 0);
};
console.log(sum(1, 2, 3, 4)); // 输出: 10
4. 没有prototype
属性
const func = () => {};
console.log(func.prototype); // 输出: undefined