我想循环访问一个gameobjects数组并调用它们的更新方法。 Gameobjects可以有不同的更新实现(例如:更新敌人不同于朋友更新),所以我创建了一个原型继承链。但我无法实现它:在遍历所有对象时,我似乎无法调用它们的更新方法:编译器说它们不存在。所以我的问题是:是否有可能在Javascript中循环共享相同基类的对象数组,并调用可以被不同子类覆盖的方法?Javascript从数组中调用对象方法?
这是我到目前为止,不知道我哪里错了...:
//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!!
}
谢谢你,现在的工作。我在错误的地方寻找问题。 – svanheste 2014-12-13 15:07:56