【发布时间】:2021-05-03 16:58:06
【问题描述】:
我知道其中一个区别是 Function 类型的实例变量自动绑定到类。例如:
class Dog {
sound = 'woof'
bark() {
console.log(this)
}
boundBark = () => {
console.log(this)
}
}
const fido = new Dog()
fido.bark() // woof
fido.boundBark() // woof
const bark = fido.bark
bark() // undefined
const boundBark = fido.boundBark
boundBark() // woof
Dog { sound: 'woof', boundBark: [Function: boundBark] }
Dog { sound: 'woof', boundBark: [Function: boundBark] }
undefined
Dog { sound: 'woof', boundBark: [Function: boundBark] }
为什么会这样?这两种编写实例函数的方式还有其他区别吗?
【问题讨论】:
-
调用箭头函数不会建立
this绑定。 -
bark是存在于Dog原型上的方法,在所有实例之间共享。boundBark是一个实例属性,它包含一个箭头函数,每个实例都有一个。 -
"Function 类型的实例变量自动绑定到类" 如果这里的“实例变量”是一个自己的属性,只有当该方法直接在类中用箭头函数定义。
-
@Pointy 另外,我相信您的解释并不准确。箭头函数是唯一真正保留 this 绑定的函数。
-
@Tim 不,Pointy 完全正确。请参阅How does the “this” keyword work? 以获得更完整的说明,但非箭头 函数将在调用时确定
this的值。箭头函数不是这样——调用它们不会改变this。
标签: javascript function this bind