I've got this strange behavior and even if I can easily workaround it I'd like to know why this happens.
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 () {
...
}
}
So I'm clearly missing something:
this.setKeybindings() gets successfully executed from within the init method.
this.processInput() throws an error.
I don't need a workaround, i solved it by using a local reference, like this:
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()
}
}
I'd like to know why 'this' works only in some methods (like init) while it doesn't in others (like update).