箭头函数主要应用场景
- 作为回调函数:在需要传递函数作为参数的场景中,如数组的迭代方法(map、filter、reduce 等)、事件处理程序等,箭头函数能使代码更简洁。例如在
setTimeout
中使用箭头函数:
setTimeout(() => {
console.log('Hello, Arrow Function!');
}, 1000);
- 简化函数表达式:当函数体逻辑简单时,箭头函数无需使用
function
关键字,简化了函数定义。比如定义一个简单的加法函数:
const add = (a, b) => a + b;
console.log(add(2, 3));
在数组方法中使用箭头函数
- map 方法:用于创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers);
- filter 方法:创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers);
箭头函数与普通函数在 this 指向方面的区别
- 普通函数:
this
的指向在函数被调用时确定,取决于函数的调用方式。在全局作用域中调用,this
指向全局对象(浏览器中是window
,Node.js 中是global
);作为对象方法调用时,this
指向该对象;通过call
、apply
、bind
方法调用时,this
指向指定的对象。
const obj = {
value: 10,
getValue: function() {
return this.value;
}
};
console.log(obj.getValue());
- 箭头函数:没有自己的
this
,它的this
继承自外层作用域(词法作用域)。无论在何处调用,箭头函数的this
始终指向其定义时所在的作用域中的this
。
const obj = {
value: 10,
getArrowValue: () => {
return this.value;
}
};
console.log(obj.getArrowValue());
// 这里输出的是全局作用域中的value,在浏览器中可能是undefined