1 回答
TA贡献1801条经验 获得超8个赞
你失去了上下文:
class Tank {
draw() {
console.log('draw');
}
update() {
this.draw();
}
}
const tank = new Tank();
// Call method of instance. Works
tank.draw();
// Set this method as listener.
// Dont works, cause method called from event context (window)
window.addEventListener("event1", tank.update, true);
// Set anonimous listener, which call method. Works
window.addEventListener("event2", () => tank.update(), true);
// Set method as listener and bind right context. Also works
window.addEventListener("event3", tank.update.bind(tank), true);
window.dispatchEvent(new Event("event1"));
window.dispatchEvent(new Event("event2"));
window.dispatchEvent(new Event("event3"));
添加回答
举报