Language: Javascript
Operating System: Ubuntu 14.04
Browser: Tested in Chromium, Chrome, Firefox.
Background
I'm making a HTML5 Canvas game that has various collectable items. The superclass for these items is Collectable
, which has a render()
function:
Collectable.prototype.render = function(){
// renders the collectables
}
There are different subclasses of Collectable
, all of which delegate render()
to the superclass. For example:
var Heart = function(x, y) {
Collectable.call(this, x, y);
}
Heart.prototype = Object.create(Collectable.prototype);
I instantiate my collectables by first creating an array containing all of my collectables:
var collectables = [];
var numOfEach = 5;
// IIFE so as to not pollute global scope
(function() {
for (var i = 0; i < numOfEach; i++) {
// TODO: make this cleaner
var heart = new Heart(100, 200);
collectables.push(heart);
var gemBlue = new GemBlue(100, 200);
collectables.push(gemBlue);
var gemOrange = new GemOrange(100, 200);
collectables.push(gemOrange);
}
})();
Then in my game loop file, I have a renderEntities()
function that repeatedly calls individual render methods on my objects:
function renderEntities() {
// render my other objects
...
// render collectables
collectables.forEach(function() {
// test what 'this' is bound to
console.log(this);
// call render method
this.render();
});
}
...however in this case this
is bound to window
and therefore this.render
is not a function.
Question
How do I bind this
to each individual element of my collectables
array?
My research
I've read the documentation for the bind
function, but I'm afraid I can't work out how this would be applied with forEach()
and my anonymous function.
I then found this existing question which explained how forEach
takes an optional parameter to set this
. After reading the documentation on forEach
I tried the following with unsuccessful results:
collectables.forEach(function() {
// test what 'this' is bound to
console.log(this);
// call render method
this.render();
}, this);
...which obviously had the same effect of setting this
to the global object.
collectables.forEach(function() {
// test what 'this' is bound to
console.log(this);
// call render method
this.render();
}, collectables);
...this got me a little closer, as this
is bound to the collectables array as a whole, but obviously this.render
is still not a function. I can't see what argument I can use here in forEach
to bind this
to each element of the array.
I have a feeling that after typing all this out the answer will be very simple. I'm relatively new to the concept of this
so go easy on me!
I haven't found another question that answers this for me, or at least one that I'm able to understand given my level of knowledge. For example, I have considered the following questions: