如何在回调中访问Class?

时间:2018-01-31 09:04:37

标签: javascript class ecmascript-6 this

我正在玩ES6并陷入“这个”。我有按钮,我想当用户点击按钮时按钮的文本应更新为“通过”。

HTML

<button type='button'>Click Me</button>

JS

class Test {
  constructor(){
    this.result = "Passed";
  }

  run() {
    alert('clicked');
    this.textContent = test.result;
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run ,false)
  }
}

let obj = new Test();
obj.btnClik();

您可能会看到它的实际效果:JSfiddle link

1 个答案:

答案 0 :(得分:1)

有几个错误

  • this上下文绑定到事件处理程序
  • 设置textContent的{​​{1}}而不是event.target

this

<强>演示

  run(event) {
    event.target.textContent = this.result; //set target of event.target
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run.bind( this ) ,false); //notice bind this
  }
class Test {
  constructor(){
    this.result = "Passed";
  }

  run(event) {
    event.target.textContent = this.result; //set target of event.target
  }

  btnClik() {
     document.querySelector('button').addEventListener('click', this.run.bind( this ) ,false); //notice bind this
  }
}

let obj = new Test();
console.log(obj);
obj.btnClik();