在 JavaScript 中,=> 符号称为 箭头函数(Arrow Function),也称为胖箭头函数。
1. 基本语法 ★
// 传统函数表达式
const add = function(a, b) {
return a + b;
};
// 箭头函数(等价写法)
const add = (a, b) => {
return a + b;
};
// 更简洁的箭头函数
const add = (a, b) => a + b;
2. 核心特性
(1) 更简洁的语法
// 单参数可省略括号
const square = x => x * x;
// 无参数需要空括号
const sayHello = () => console.log('Hello');
// 多参数需要括号
const multiply = (a, b) => a * b;
(2) 隐式返回
// 函数体只有一行时可省略 return
const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2); // [2, 4, 6]
// 返回对象需要括号包裹
const getUser = () => ({ name: 'Alice', age: 25 });
(3) 不绑定 this(最重要特性)
function Counter() {
this.count = 0;
// 传统函数:this 指向调用者
setInterval(function() {
this.count++; // ❌ this 指向 window(非严格模式)
}, 1000);
// 箭头函数:this 继承外层作用域
setInterval(() => {
this.count++; // ✅ this 指向 Counter 实例
}, 1000);
}
3. 常见使用场景
(1) 数组方法回调
const numbers = [1, 2, 3, 4];
// 传统写法
const even = numbers.filter(function(n) {
return n % 2 === 0;
});
// 箭头函数写法
const even = numbers.filter(n => n % 2 === 0);
(2) Vue/React 事件处理
<template>
<button @click="handleClick">点击</button>
</template>
<script>
export default {
methods: {
// 传统写法
handleClick: function() {
console.log(this); // ✅ 指向 Vue 实例
},
// 箭头函数写法(不推荐在 methods 中使用)
handleClick: () => {
console.log(this); // ❌ 指向 undefined(严格模式)
}
}
}
</script>
(3) Promise 链式调用
fetch('/api/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
4. 与传统函数的区别
| 特性 | 传统函数 | 箭头函数 |
|---|---|---|
| this 绑定 | 动态绑定(调用者决定) | 词法绑定(定义时确定) |
| arguments 对象 | ✅ 有 | ❌ 无(用剩余参数替代) |
| 构造函数 | ✅ 可用 new 调用 | ❌ 不能用作构造函数 |
| 原型属性 | ✅ 有 prototype | ❌ 无 prototype |
5. 注意事项
(1) 不适合用在 methods 中
// Vue 示例(不推荐)
export default {
data() {
return { count: 0 };
},
methods: {
// ❌ 箭头函数:this 不指向 Vue 实例
badMethod: () => {
console.log(this.count); // undefined
},
// ✅ 传统函数:this 正确指向
goodMethod() {
console.log(this.count); // 0
}
}
}
(2) 事件处理器的 this 问题
const button = document.querySelector('button');
// ❌ 箭头函数:this 指向 window
button.addEventListener('click', () => {
console.log(this); // Window
});
// ✅ 传统函数:this 指向 button 元素
button.addEventListener('click', function() {
console.log(this); // <button>
});
6. 记忆技巧
- 箭头符号:
=>像箭头指向返回值 - this 绑定:想象箭头”射向”定义时的上下文
- 简洁性:比
function关键字更短
总结
- 名称:箭头函数(Arrow Function)
- 核心优势:简洁语法 + 词法
this绑定 - 适用场景:数组方法、回调函数、需要固定
this的场合 - 注意事项:避免在需要动态
this的场景使用
箭头函数是现代 JavaScript 开发的重要特性,让代码更简洁易读!
