我写了以下代码.这里getGreeting已经绑定了Salutation.当使用getGreeting绑定时,它仍然使用类的上下文调用.myNamebind()Salutation
let myName = {
name: 'John'
}
class Salutation {
constructor() {
this.name = 'Mike';
this.getGreeting = this.getGreeting.bind(this)
}
getGreeting() {
return `Hi. My name is ${this.name}`
}
}
const salutation = new Salutation();
console.log(salutation);
boundFunction = salutation.getGreeting.bind(this);
boundFunction();// My name is Mike
boundFunction = salutation.getGreeting.bind(myName);
boundFunction();// My name is Mike
Run Code Online (Sandbox Code Playgroud)
你不能.
bind创建一个新函数(B),用特定的函数调用原始函数(A)this.
尝试重新绑定它会创建另一个新函数(C),它使用特定的函数调用前一个函数(B)this.然而,B并不关心this它的价值是什么,它仍然用它最初被告知要使用的值来调用A.
| 归档时间: |
|
| 查看次数: |
54 次 |
| 最近记录: |