箭头函数
箭头函数(Arrow Function)是 JavaScript 中的一种简洁函数语法,于 ES6(2015)引入,主要特点是语法简洁,且不绑定自身的 this、arguments 等,适用于简化函数定义和处理上下文绑定问题。
一、基本语法
箭头函数的核心是用 =>(“箭头”)连接参数和函数体,语法形式如下:
0.无函数名
data是参数

1. 无参数
// 传统函数
function sayHi() {
console.log('Hi');
}
// 箭头函数(无参数时用 () 表示)
const sayHi = () => {
console.log('Hi');
};
2. 单个参数
// 传统函数
function double(num) {
return num * 2;
}
// 箭头函数(单个参数可省略 ())
const double = num => {
return num * 2;
};
3. 多个参数
// 传统函数
function sum(a, b) {
return a + b;
}
// 箭头函数(多个参数必须用 () 包裹)
const sum = (a, b) => {
return a + b;
};
4. 函数体只有一行代码(可省略 {} 和 return)
// 省略 {} 和 return,自动返回结果
const double = num => num * 2;
const sum = (a, b) => a + b;
5. 返回对象(需用 () 包裹对象,避免 {} 被解析为函数体)
// 错误写法({} 会被当作函数体,而非对象)
const getUser = () => { name: 'Alice', age: 20 }; // 无效
// 正确写法(用 () 包裹对象)
const getUser = () => ({ name: 'Alice', age: 20 });
二、核心特性(与传统函数的区别)
- 不绑定 this
箭头函数没有自己的 this,它的 this 继承自外层作用域的 this(定义时的上下文,而非调用时)。
这解决了传统函数中 this 指向易变的问题(如回调函数中 this 丢失)。
const obj = {
name: 'Vue',
// 传统函数:this 指向调用者(obj)
sayName1: function() {
console.log(this.name); // 输出 'Vue'
},
// 箭头函数:this 继承外层作用域(此处外层是全局,浏览器中为 window)
sayName2: () => {
console.log(this.name); // 输出 undefined(window 没有 name 属性)
},
// 箭头函数在回调中更友好
delaySayName: function() {
// 传统函数回调:this 指向 window
setTimeout(function() {
console.log(this.name); // 输出 undefined
}, 1000);
// 箭头函数回调:this 继承自 delaySayName 的 this(即 obj)
setTimeout(() => {
console.log(this.name); // 输出 'Vue'
}, 1000);
}
};
obj.sayName1(); // 'Vue'
obj.sayName2(); // undefined
obj.delaySayName(); // 1秒后输出 'Vue'
- 不能用作构造函数
箭头函数无法通过 new 关键字调用(会报错),因为它没有 prototype 属性。
const Person = () => {};
new Person(); // 报错:Person is not a constructor
- 没有 arguments 对象
箭头函数不绑定 arguments(实参列表),若需获取参数列表,可使用剩余参数(...args)。
// 传统函数:有 arguments
function logArgs() {
console.log(arguments); // 输出 [1, 2, 3]
}
logArgs(1, 2, 3);
// 箭头函数:用剩余参数替代 arguments
const logArgs = (...args) => {
console.log(args); // 输出 [1, 2, 3]
};
logArgs(1, 2, 3);
三、适用场景
- 简短的回调函数:如数组方法(map、filter、forEach 等)中,简化代码。
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2); // [2, 4, 6]
- 需要保留外层 this 的场景:如定时器回调、事件处理中,避免 this 指向混乱。
- 简洁的工具函数:逻辑简单的函数,用箭头函数更简洁。
四、不适用场景
- 对象的方法:如上述 obj.sayName2 示例,箭头函数的 this 不指向对象本身。
- 需要 this 动态绑定的场景:如事件处理器(需 this 指向触发事件的元素)。
- 构造函数:无法通过 new 创建实例。
箭头函数的核心价值是简化语法和解决 this 绑定问题,合理使用能让代码更简洁、更易维护。
