如何使用bind方法覆盖已绑定函数的`this`值

Pre*_*rem 0 javascript

我写了以下代码.这里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)

Que*_*tin 6

你不能.

bind创建一个新函数(B),用特定的函数调用原始函数(A)this.

尝试重新绑定它会创建另一个新函数(C),它使用特定的函数调用前一个函数(B)this.然而,B并不关心this它的价值是什么,它仍然用它最初被告知要使用的值来调用A.