Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/448.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用bind方法为已绑定的函数重写`this`值_Javascript - Fatal编程技术网

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())的可能重复项的可能重复项