Javascript 如何使用bind方法为已绑定的函数重写`this`值
我已经编写了以下代码。这里的Javascript 如何使用bind方法为已绑定的函数重写`this`值,javascript,Javascript,我已经编写了以下代码。这里的getGreeting已经与saltation绑定。当getGreeting使用bind()与myName绑定时,它仍然使用saltation类的上下文调用 let myName = { name: 'John' } class Salutation { constructor() { this.name = 'Mike'; this.getGreeting = this.getGreeting.bind(this)
getGreeting
已经与saltation
绑定。当getGreeting
使用bind()
与myName
绑定时,它仍然使用saltation
类的上下文调用
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
你不能
bind
创建一个新函数(B),该函数使用特定的this
调用原始函数(a)
尝试重新绑定它会创建另一个新函数(C),该函数使用特定的this
调用以前的函数(B)。B、 但是,不管this的值是多少,它仍然使用最初告诉它使用的值调用A。您不能
bind
创建一个新函数(B),该函数使用特定的this
调用原始函数(a)
尝试重新绑定它会创建另一个新函数(C),该函数使用特定的this
调用以前的函数(B)。B、 但是,不管这个的值是什么,它仍然使用它最初被告知要使用的值调用A。我唯一能做的事情就是在类本身内部使用上下文:
const myName={
名字:“约翰”
};
班级敬礼{
构造函数(){
this.name='Mike';
this.tmpContext=此;
}
getGreeting(){
常量func=函数(){
return`Hi.My name是${this.name}`;
}.bind(this.tmpContext);
返回func();
}
}
持续称呼=新称呼();
saltation.tmpContext=myName;
log(saltation.getGreeting());
saltation.tmpContext=称呼;
log(saltation.getGreeting())代码>我唯一能做的就是在类本身内部处理上下文:
const myName={
名字:“约翰”
};
班级敬礼{
构造函数(){
this.name='Mike';
this.tmpContext=此;
}
getGreeting(){
常量func=函数(){
return`Hi.My name是${this.name}`;
}.bind(this.tmpContext);
返回func();
}
}
持续称呼=新称呼();
saltation.tmpContext=myName;
log(saltation.getGreeting());
saltation.tmpContext=称呼;
log(saltation.getGreeting())代码>的可能重复项的可能重复项