一、箭头函数的基本特性
- 语法简洁性
箭头函数使用=>
符号定义,省略function
关键字,适合快速定义匿名函数或简单表达式。
// 普通函数
function sum(a, b) { return a + b; }
// 箭头函数
const sum = (a, b) => a + b;
若函数体为单行表达式,可省略 {}
和 return
。
-
匿名性
箭头函数均为匿名函数,不能通过function
命名。 -
隐式返回对象
返回对象字面量时需用()
包裹,避免与函数体的大括号冲突:
const getObj = id => ({ id: id }); // 正确
二、this
指向的核心差异
-
普通函数的
this
-
动态绑定:根据调用方式确定
this
(如对象方法调用、构造函数调用等)。 -
可通过
call
、apply
、bind
显式修改this
指向。
-
-
示例:
const obj = {value: 10,getValue: function() { return this.value; }
};
obj.getValue(); // 10(this指向obj)
-
箭头函数的
this
-
词法绑定:在定义时捕获外层非箭头函数的
this
,且无法通过调用方式改变。 -
**无自身
this
**:相当于“继承”父级上下文的this
。
-
-
示例:
function Timer() {this.seconds = 0;// 箭头函数捕获外层Timer的thissetInterval(() => this.seconds++, 1000);
}
const timer = new Timer(); // this.seconds每秒自增
三、箭头函数与普通函数的其他区别
四、this
的具体应用场景对比
-
对象方法
- 普通函数:
this
指向调用对象。
const obj = {value: 10,getValue() { return this.value; } // 返回10 };
- 箭头函数:
this
指向外层作用域(如全局window
)。
const obj = {value: 10,getValue: () => this.value // 返回undefined(全局无value) };
- 普通函数:
-
事件处理函数
-
普通函数:
this
指向触发事件的 DOM 元素。 -
箭头函数:
this
指向定义时的外层作用域(可能不符合预期)。
-
-
高阶函数(如
map
、setTimeout
)
优先使用箭头函数避免this
丢失:
// 传统函数需绑定this
arr.map(function(item) { return item * this.factor; }.bind(this));
// 箭头函数自动捕获外层this
arr.map(item => item * this.factor);
五、适用场景总结
-
优先使用箭头函数:
-
需要固定
this
的场景(如回调函数、事件处理)。 -
简化单行表达式(如数组操作
map
/filter
)。
-
-
避免使用箭头函数:
- 对象方法、构造函数、需要
arguments
的场景。
- 对象方法、构造函数、需要