Reputation: 91
var spaceship = {
fps : 10,
speed : 1,
traveled : 0,
currency : 0,
initialize : function() {
this.update();
},
update : function() {
this.traveled += this.speed/this.fps;
setTimeout(this.update, 1000/this.fps);
this.render();
},
render : function() {
$("#spaceshipbg").attr("background-position", "0px "+this.traveled+"px");
}
};
$(document).ready(function() {
spaceship.initialize();
});
So this is my code, Whenever i load up the page, i get an error with the line "this.render()". I can't see the problem here, i can successfully call this.update() from the initialize function, but when i call this.render() it says it's undefined
Upvotes: 0
Views: 655
Reputation: 7771
When initialize
is called, it calls this.update()
. update()
itself works, even the first call to this.render()
. However, setTimeout
will invoke update
, but it will not call it on your object. Therefore, this
will not reference your object anymore. this.render()
is undefined.
For more information about the problem, read this.
The solution might look like this:
update : function() {
var self = this;
this.traveled += this.speed/this.fps;
setTimeout(function() {
// Enforce the correct context
self.update();
}, 1000/this.fps);
this.render();
},
Upvotes: 1