1 回答

TA贡献1830条经验 获得超3个赞
一种方法是动态创建 的绑定版本并改用它:gameOn()
{
// ...
start() {
for (let coin of coins) {
this.moveCoin(coin);
}
if (this.boundGameOn === undefined) {
this.boundGameOn = this.gameOn.bind(this);
}
window.addEventListener("keydown", this.boundGameOn)
},
stop() {
window.removeEventListener("keydown", this.boundGameOn);
},
// ...
}
理想情况下,您会在构造函数中执行此操作。如果你有一个构造函数而不是一个对象文本,你可以这样做:
function GameObject () {
this.boundGameOn = this.gameOn.bind(this)
}
GameObject.prototype = {
// rest of code ..
}
事实上,在 React 应用程序中,看到这种设计模式并不少见:
function GameObject () {
this.gameOn = this.gameOn.bind(this); // MAGIC!!
}
GameObject.prototype = {
// ...
start() {
for (let coin of coins) {
this.moveCoin(coin);
}
window.addEventListener("keydown", this.gameOn)
},
stop() {
window.removeEventListener("keydown", this.gameOn);
},
// ...
}
MAGIC 行确保内部始终指向游戏对象,因为您正在用其自身的绑定版本覆盖它。thisgameOn()
这在ES6类语法中看起来稍微干净一些(只是稍微有点,我个人对这两种语法都没有偏好):
class GameObject {
constructor () {
this.gameOn = this.gameOn.bind(this); // MAGIC!!
}
// ...
start() {
for (let coin of coins) {
this.moveCoin(coin);
}
window.addEventListener("keydown", this.gameOn)
}
stop() {
window.removeEventListener("keydown", this.gameOn);
}
// ...
}
使用为ES7提出的实验性类属性语法,它甚至更简单:你可以只使用箭头函数(现在不要直接使用它,2020年中期,因为Safari不支持这个,但如果你使用Babel或Typescript,你可以编译到ES6):
class GameObject {
// ...
start = () => {
for (let coin of coins) {
this.moveCoin(coin);
}
window.addEventListener("keydown", this.gameOn)
}
stop = () => {
window.removeEventListener("keydown", this.gameOn);
}
// ...
}
在本例中由箭头函数绑定。this
添加回答
举报