I'm currently attempting to iterate through an array of game objects and invoke their update methods. The challenge is that game objects may have different update implementations - for example, the update function for an enemy is different from that of a friend. To address this, I have set up a prototype inheritance chain. However, I'm encountering an issue: when I loop through all objects, I'm unable to call their update methods as the compiler indicates that they don't exist. My question is: Is it feasible in Javascript to iterate through an array of objects that have a shared base class and invoke a method that can be overridden by various subclasses?
Here is the current state of my code, but I'm unsure where the problem lies:
// Define the base GameObject class
function GameObject(name) {
this.name = name;
};
GameObject.prototype.update = function(deltaTime) {
throw new Error("Cannot call abstract method!");
};
// Enemy class inherits from GameObject
function Enemy() {
GameObject.apply(this, arguments);
};
Enemy.prototype = new GameObject();
Enemy.prototype.constructor = Enemy;
Enemy.prototype.update = function(deltaTime) {
alert("In the update method of Enemy: " + this.name);
};
var gameobjects = [];
// Add an enemy to the array
gameobjects[gameobjects.length] = new Enemy("weirdenemy");
// This loop is not working as expected and reports 'gameobject doesn't have update method'
for (gameobject in gameobjects) {
gameobject.update(1); // This doesn't work!
}