[英]Accessing object properties from object itself
I'm having a little trouble learning object-oriented Javascript. 我在学习面向对象的Javascript时遇到了一些麻烦。 I have two classes called Cosmos
and Background
, Cosmos
looks like this: 我有两个名为Cosmos
和Background
类, Cosmos
看起来像这样:
// js/Cosmos.js
function Cosmos() {
this.background = new Background();
// Fire game loop
this.ticker = setInterval(this.tick, 1000 / 60);
}
// Main game loop
Cosmos.prototype.tick = function() {
console.log(this.background);
}
When the main game loop ticks, I get undefined
in console. 当主游戏循环滴答时,我在控制台中undefined
。 I don't quite understand this because this.background
is a property of the Cosmos
class, so it should be accessible by the methods defined in the Cosmos
class, no? 我不太明白这一点,因为this.background
是Cosmos
类的一个属性,所以它应该可以通过Cosmos
类中定义的方法访问,不是吗?
If I go back to my index.html
page's script tag and change it to this: 如果我回到我的index.html
页面的脚本标记并将其更改为:
// Lift off
var cosmos = new Cosmos();
console.log(cosmos.background);
it works and the Background
object gets logged to the console. 它工作, Background
对象被记录到控制台。 Can anyone offer an explanation and tell me how I can access the properties of Cosmos
from within Cosmos.tick
? 任何人都可以提供解释并告诉我如何从Cosmos.tick
访问Cosmos
的属性?
Edit: Turns out the problem is something to do with setInterval()
, because if I do this the proper object is logged to console: 编辑:结果问题与setInterval()
,因为如果我这样做,正确的对象会记录到控制台:
function Cosmos() {
this.background = new Background();
// Fire game loop
//this.ticker = setInterval(this.tick, 1000 / 60);
this.tick();
}
// Main game loop
Cosmos.prototype.tick = function() {
console.log(this.background);
}
still don't know the best way around it, though. 但是,他仍然不知道最好的方法。
When the function is called from setInterval
, this
will not be bound to the object anymore. 当功能被称为从setInterval
, this
将不再绑定到对象。
This is a quick fix to your problem: 这是您的问题的快速解决方案:
// js/Cosmos.js
function Cosmos() {
var self = this;
this.background = new Background();
// Fire game loop
this.ticker = setInterval(function () {
self.tick();
}, 1000 / 60);
}
By using the self
variable, the inner function gets to access this
. 通过使用self
变量,内部函数可以访问this
。
this
in function scope for setInterval
is window
, but you can change function scope via .bind
(or just redeclare this
like the other answer says): this
在setInterval
函数范围是window
,但你可以通过.bind
更改函数范围(或者像其他答案一样重新声明this
):
this.ticker = setInterval(this.tick.bind(this), 1000 / 60);
http://jsfiddle.net/ExplosionPIlls/SwQ5V/ http://jsfiddle.net/ExplosionPIlls/SwQ5V/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.