【发布时间】:2015-02-12 03:22:16
【问题描述】:
我正在尝试遍历一组游戏对象并调用它们的更新方法。 游戏对象可以有不同的更新实现(例如:敌人的更新与朋友的更新不同),所以我创建了一个原型继承链。但我无法让它工作:在遍历所有对象时,我似乎无法调用它们的更新方法:编译器说它们不存在。所以我的问题是:是否可以在 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!!
}
【问题讨论】:
标签: javascript arrays inheritance methods overriding