我正在使用 ES6,但陷入了“this”。我有按钮,我希望当用户单击按钮时,按钮的文本应更新为“通过”。
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
最佳答案
有几个错误
- 将
this
上下文绑定(bind)到事件处理程序 - 设置
event.target
的textContent
而不是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();
<button type='button'>Click Me</button>
关于javascript - 如何在回调中访问类的 this ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538261/