面试题答案
一键面试ES6+箭头函数相较于传统函数表达式的优势
- 简洁的语法:箭头函数语法更为简洁,例如传统函数
function add(a, b) { return a + b; }
,箭头函数可写成const add = (a, b) => a + b;
。 - 词法作用域:箭头函数没有自己的
this
,它的this
继承自外层作用域,避免了传统函数中因this
指向问题导致的错误。例如在构造函数内部使用传统函数,this
可能指向全局对象或其他意想不到的对象,而箭头函数能保证this
指向外层作用域。 - 没有 arguments 对象:在箭头函数中,不存在
arguments
对象,如果需要获取参数,可使用剩余参数...args
,这使得代码意图更清晰,例如const sum = (...args) => args.reduce((acc, cur) => acc + cur, 0);
。
箭头函数适合使用的实际场景
- 异步操作中的回调:在处理
setTimeout
、Promise
等异步操作时,箭头函数简洁的语法和词法作用域特性很有用。例如:
setTimeout(() => {
console.log('This is an arrow function in setTimeout');
}, 1000);
在 Promise
的 then
方法中使用箭头函数:
fetch('https://example.com/api/data')
.then(response => response.json())
.then(data => console.log(data));
- 数组方法回调:在
map
、filter
、reduce
等数组方法中,箭头函数使代码更简洁易读。例如:
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map(num => num * num);
const filteredNumbers = numbers.filter(num => num % 2 === 0);
const sum = numbers.reduce((acc, num) => acc + num, 0);