从JavaScript中的另一个方法属性中引用对象方法属性
Refer to object method property from another method property in JavaScript
我有这种奇怪的行为,即使我可以很容易地解决它,我也想知道为什么会发生这种情况。
function Game () {
this.viewport = { ... };
this.player = Player;
this.renderer = { ... };
this.stage = { ... };
this.init = function () {
//THIS GETS EXECUTED
this.setKeyBindings();
}
this.run = function () {
//THIS WORKS TOO
requestAnimFrame(this.update);
}
this.update = function () {
//BAD! THROWS UNDEFINED IS NOT A FUNCTION
//HERE I NEED TO USE A REFERENCE HERE
this.processInput();
this.renderer.render(this.stage);
this.handleLogic();
//EVEN THIS ONE WON'T WORK, BUT IT WORKED IN init()!
requestAnimFrame(this.update);
};
//METHODS ARE DEFINED THE SAME WAY
this.processInput = function () {
...
};
this.handleLogic = function () {
...
};
this.setKeyBinding = function () {
...
}
}
所以我显然错过了一些东西:
this.setKeybindings()从init方法中成功执行。
this.processInput()引发错误。
我不需要变通方法,我通过使用本地引用解决了它,比如:
function Game () {
var reference = this;
.......
this.update = function () {
//NOW WORKS
reference.processInput();
reference.handleLogic();
reference.renderer.render(reference.stage);
requestAnimFrame(reference.update);
}
this.init = function () {
//THIS ONE WORKS EVEN USING 'this'
this.setKeyBindings()
}
}
我想知道为什么"this"只在某些方法(如init)中有效,而在其他方法(如update)中无效。
声明局部变量,并将this分配给它,并在任何地方使用它:
function Game () {
var me = this;
.......
me.update = function () {
me.processInput();
me.handleLogic();
me.renderer.render(me.stage);
requestAnimFrame(me.update);
}
}
这将解决引用的问题
相关文章:
- 为什么NgModelController属性/方法以$开头
- 如何使用设置属性方法在jquery中更改css
- 全局向对象添加属性/方法
- AngularJS $http.delete 在“类型错误:无法分配给只读属性'方法'”中中断
- 添加属性/方法的明确最佳方法
- 扩展类时继承而不是覆盖属性/方法
- Javascript子类对象不保留基类的属性/方法
- 将模型属性方法发送到客户端 Sails Angular
- 错误:参数 4 的值无效.属性“方法”:意外属性
- 类型错误:无法读取 nodejs 应用程序中未定义的属性“方法”
- 属性/方法无法初始化indexedDB
- 在javascript中定义属性方法的适当模式;类”;
- 创建两个函数来计算对象属性/方法
- 当getElementById返回null时,取消对属性/方法的访问
- 自定义属性方法如何在Sails js中工作
- 通过js中的数组属性方法进行迭代
- 为什么要添加属性/方法到视图模型AFTER定义
- 在Angular中,在闭包中引用服务属性/方法最合适的方式是什么?
- 列出一个对象的所有属性/方法
- Javascript:添加属性方法问题