请考虑代码:的Javascript循环通过原型
// define the GameObject constructor function
var GameObject = function(width, height) {
this.x = Math.floor((Math.random() * myCanvasWidth) + 1);
this.y = Math.floor((Math.random() * myCanvasHeight) + 1);
this.width = width;
this.height = height;
return this;
};
// (re)define the GameObject prototype object
GameObject.prototype = {
x: 0,
y: 0,
width: 5,
width: 5,
draw: function() {
myCanvasContext.fillRect(this.x, this.y, this.width, this.height);
}
};
然后,我们可以实例化游戏物体的100倍。
var x = 100,
arrayOfGameObjects = [];
do {
arrayOfGameObjects.push(new GameObject(10, 10));
} while(x--);
现在我们有100个GameObjects,其中所有共享相同的原型和定义的拉伸方法,所述应用程序内的这大大节省了存储器的阵列。
当我们调用draw方法时,它会引用完全相同的函数。
var GameLoop = function() {
for(gameObject in arrayOfGameObjects) {
gameObject.draw(); // this is my problem. Is this correct? gameObject is simply and index who draw() method gets executed
}
};
我的问题是最后一行代码的方法draw()正在执行。由于gameObject只是一个索引,draw()方法如何执行?该索引不包含任何对象。它只是一个索引权?
Here是一个链接
你是对的,但由于即时通讯有问题,我需要在这种特殊情况下的帮助 –
需要帮助什么?上面的代码回答你的问题... – BenM
看到我的最后一行代码,其中draw()方法得到执行,这是正确的,因为var gameObject只保存索引no对象如何执行draw方法? –