Reputation: 71
I am trying to loop through an array of gameobjects and call their update methods. Gameobjects can have different update implementations (eg: update of enemy is different from update of friend), so I created an prototype inheritance chain. But I can't get it to work: while looping through all objects I don't seem to be able to call their update methods: the compiler says they don't exist. So my question is: is it possible in Javascript to loop trough an array of objects that share the same base class and call a method on them that can be overwritten by different sub-classes?
This is what I have so far, don't know where I went wrong...:
//base gameobject class
function GameObject(name) {
this.name = name
};
GameObject.prototype.update = function(deltaTime) {
throw new Error("can't call abstract method!")
};
//enemy inherits from gameobject
function Enemy() {
GameObject.apply(this, arguments)
};
Enemy.prototype = new GameObject();
Enemy.prototype.constructor = Enemy;
Enemy.prototype.update = function(deltaTime) {
alert("In update of Enemy " + this.name);
};
var gameobjects = new Array();
// add enemy to array
gameobjects[gameobjects.length] = new Enemy("weirdenemy");
// this doesn't work: says 'gameobject doesn't have update method'
for (gameobject in gameobjects) {
gameobject.update(1); // doesn't work!!
}
Upvotes: 0
Views: 3241
Reputation: 239453
Its not a problem with your Inheritance chain, but with this construct
for(gameobject in gameobjects){
gameobject.update(1); // doesn't work!!
}
When you iterate an Array
with for..in
, the variable will have the index values only. So, gameobject
will have 0
, 1
.. like that, in every iteration. It is not recommended to use for..in
to iterate an Array.
You might want to use, Array.prototype.forEach
, like this
gameobjects.forEach(function(gameObject) {
gameObject.update(1);
});
Upvotes: 1
Reputation: 5255
Try this, it works for me: =)
gameobjects.forEach(function(gameobject){
gameobject.update(1); // doesn't work!!
});
Upvotes: 0
Reputation: 413712
When you iterate through an array with for ... in
, the values of the loop variable will be the keys to the array, not the values.
You really shouldn't iterate through arrays that way anyway:
for (var i = 0; i < gameobjects.length; ++i)
gameobjects[i].update(1);
Upvotes: 0