箭头函数基础 📚
箭头函数(Arrow Function)是ES6新增的语法糖,用=>操作符定义函数:
// 传统函数
const sum = function(a, b) {
return a + b;
}
// 箭头函数
const sum = (a, b) => a + b; // 单行可省略return
优缺点 🔍
✅ 优点
-
简洁的语法
单行代码无需写{}和return:const square = x => x * x; // 比传统函数少7个字符! ✨ -
自动绑定this
解决回调函数中this丢失的经典问题:document.addEventListener('click', function() { setTimeout(() => { console.log(this); // 指向document ✅ }, 100); }); -
适合纯函数场景
无副作用的设计让代码更可预测:const cleanData = arr => arr.filter(item => item.isValid);
❌ 缺点
-
无法作为构造函数
const Animal = () => {}; new Animal(); // ❌ TypeError: Animal is not a constructor -
没有arguments对象
需改用剩余参数:const showArgs = (...args) => console.log(args); // ✅ const oldShowArgs = function() { console.log(arguments); } -
过度简写可能降低可读性
// 箭头函数嵌套时可能难以理解 const magic = a => b => c => a + b + c; // 需要分步解析 😵
实战中的妙用 🔥
案例1:数组操作
// 筛选及格分数
const passed = scores.filter(score => score >= 60);
// 计算总分(如项目中的reduce用法)
const total = list.reduce((acc, item) => acc + item.score, 0);
案例2:Vue计算属性
computed: {
totalScore() { // ✅ 正确:使用普通函数保持this指向
return this.list.reduce((total, item) => total + item.score, 0);
}
// ❌ 错误:箭头函数会导致this指向错误
// totalScore: () => this.list.reduce(...)
}
经典面试题 💡
const obj = {
name: 'JS',
print: () => {
console.log(this.name); // 输出?
}
};
obj.print(); // 输出undefined(箭头函数this指向window)
1. 箭头函数的 this 继承自外层作用域
箭头函数 print 定义在 obj 对象内部,但对象字面量({})不形成自己的作用域。因此,print 的 this 会向外查找,最终指向全局作用域(浏览器中为 window 对象,Node.js 中为 global)。
2. 为什么输出 undefined?
- 在浏览器中,全局作用域的
this是window对象。 window默认没有name属性,或默认值为空字符串。- 若未显式设置
window.name,this.name即为undefined。
总结 🌟
箭头函数就像代码界的瑞士军刀🗡️——在合适的场景使用能让代码更优雅简洁,但也要注意它的特性边界。记住:没有最好的语法,只有最合适的用法!
🎯 学习建议:多在实际项目中尝试,结合Chrome/Edge调试工具观察this指向变化,理解会更深刻哦~