🛺 JavaScript 深入箭头函数
至此,JavaScript 中已经有不少的 例子 使用箭头函数简化代码。除了简化代码的好处,还有许多特殊有用的特性。
在 JavaScript 中不少的实用方法 包括内建函数,都有用到传入一个 执行的回调函数(小函数)之处,可以使用箭头函数,例如:
arr.forEach(func):对数组中的每一个元素都执行func。setTimeout(func):func转为内建调度器执行。
当创建一个函数并且将它传递到某一个地方,但是不想离开当前的上下文,就可以使用 箭头函数。
# 箭头函数没有 this
箭头函数没有 this ,如果要用到 this ,会从外部获取。
🌰 例子:
let group = {
title: 'Group',
members: ['a', 'b', 'c'],
showList() {
this.members.forEach(member => console.log(this.title + ': ' + member))
}
}
group.showList()
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
此处
forEach()中使用了 箭头函数,所以其中this.title的this从外部获取,与showList相同即group。如果使用
function(student){...}就会出错,因为这样声明函数的this的默认值为this = undefined。
注意
不能对箭头函数 ** 使用 new **。不具有 this 表明了另一种限制:箭头函数不能用作 构造器。所以不能用 new 调用箭头函数。
提示
箭头函数与 bind 对比:
bind创建了一个原来函数的绑定上下文对象的版本。- 箭头函数没有创建任何的绑定,箭头函数只是没有
this。this的查找与常规变量的搜索方式相同,在外部的词法环境中查找。
# 箭头函数没有 arguments
当需要使用 当前的 this 和 arguments 转发一个调用时,例如装饰器,使用 箭头函数 会更加方便。
🌰 例子:
function defer(f, ms) {
return function() {
setTimeout(() => f.apply(this, arguments), ms)
}
}
function sayHi(who) {
console.log(`hello ${who}`)
}
let sayHideferred = defer(sayHi, 1000)
sayHideferred('Simon')
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
如果不使用箭头函数,而使用普通的函数声明,需要创建而外的变量获取上下文对象和参数列表,以便
setTimeout内部的函数可以获取他们。function defer(f, ms) { return function(...args) { let context = this setTimeout(function(){ return f.apply(context, args) }) } }1
2
3
4
5
6
7
8
# 总结
箭头函数的特性有:
- 没有
this - 没有
arguments - 不能使用
new构造调用 - 没有
super
- 没有
箭头函数通常使用在 当前上下文中作用 的短代码。
编辑 (opens new window)
📢 上次更新: 2022/09/02, 10:18:16
