2014-12-13 20 views
0

我想循环访问一个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!! 
} 

回答

1

它不是你继承链出了问题,但这种构造

for(gameobject in gameobjects){ 
    gameobject.update(1); // doesn't work!! 
} 

当您迭代Arrayfor..in时,该变量将仅具有索引值。所以,gameobject将有0,1 ..就像那样,在每一次迭代。 It is not recommended to use for..in to iterate an Array.

您可能希望通过与for ... in数组当你迭代使用,Array.prototype.forEach,这样

gameobjects.forEach(function(gameObject) { 
    gameObject.update(1); 
}); 
+0

谢谢你,现在的工作。我在错误的地方寻找问题。 – svanheste 2014-12-13 15:07:56

0

,循环变量的值将是的阵列,而不是值。

你真的不应该通过遍历数组这样反正:

for (var i = 0; i < gameobjects.length; ++i) 
    gameobjects[i].update(1); 
0

试试这个,它为我工作:=)

gameobjects.forEach(function(gameobject){ 
     gameobject.update(1); // doesn't work!! 
    }); 
相关问题