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?
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body.
These days, most cross-browser JavaScript problems are seen: When poor-quality browser-sniffing code, feature-detection code, and vendor prefix usage block browsers from running code they could otherwise use just fine. When developers make use of new/nascent JavaScript features, modern Web APIs, etc.)
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
When a function is called, a value will be assigned to a local variable called this
inside the function.
Unless you have done something to change it (e.g. new
, bind()
, call()
, apply()
), the value will be the object on which it is called. With foo.bar()
this === foo
inside the bar
function.
this.actions[0]()
makes this
equal to the value of the actions
property
this.holder()
makes this
equal to whatever the value of this
is in the calling function.
Your function must depend on the value of this
to do whatever it does.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With