Wednesday, 21 August 2013

Don't understand why this JavaScript function can be called one way but not the other

Don't understand why this JavaScript function can be called one way but
not the other

I recently started learning JavaScript for the purpose of creating HTML5
games, and I've come across a behavior that I'm having a hard time
understanding.
As an example, I have a constructor that initializes new sprites with an
array of actions that they should carry out every time the game updates
(such as animating, moving, etc.). This JSFiddle demonstrates a basic
implementation.
Essentially, I'm confused as to why this doesn't work...
Sprite = function () {
this.actions = [this.animate];
};
Sprite.prototype = {
animate: function () { /* animate the sprite */ },
update: function () {
this.actions[0](); // doesn't do anything (?)
}
};
...but this does
Sprite = function () {
this.actions = [this.animate];
this.holder = 'whatever';
};
Sprite.prototype = {
animate: function () { /* animate the sprite */ },
update: function () {
this.holder = this.actions[0];
this.holder(); // executes animate function as desired
}
};
To my inexperienced eyes, both examples seem like they should do the exact
same thing. So why does nothing happen if I call this.actions[0]()
directly, but if I assign this.actions[0] to this.holder and then call
this.holder(), it works just fine?

No comments:

Post a Comment