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

时间:2018-05-17 14:33:15

标签: 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

2 个答案:

答案 0 :(得分:6)

你不能。

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

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

答案 1 :(得分:0)

我唯一能做的就是在班级内部玩一个上下文:

  - name: loop of uri module over the hosts group
    uri:
      url: http://{{ item }}/
      return_content: yes
    register: webpage
    with_items: 
      - "{{ groups['webserver'] }}"