2013-04-03 27 views
0

请考虑代码:的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是一个链接

回答

1

你真的应该使用您的GameLoop如下:

var GameLoop = function() { 
    for(var i = 0; i < arrayOfGameObjects.length; i++) { 
     arrayOfGameObjects[i].draw(); 
    } 
}; 
+0

你是对的,但由于即时通讯有问题,我需要在这种特殊情况下的帮助 –

+0

需要帮助什么?上面的代码回答你的问题... – BenM

+0

看到我的最后一行代码,其中draw()方法得到执行,这是正确的,因为var gameObject只保存索引no对象如何执行draw方法? –

0

使用纯for遍历数组进行迭代。

var GameLoop = function() { 
    for (var i = 0; i < arrayOfGameObjects.length; i++) { 
     arrayOfGameObjects[i].draw(); 
    } 
}; 

它实际上是不好的做法是使用for in循环的阵列上,因为它只是一个大约的方式得到你想要的索引轮。

0

余像jQuery $。每个

$.each(arrayOfGameObjects, function(i, gObject) { 
    gObject.draw(); 
}); 

否则如所描述的通过其他使用阵列长度使用与迭代。

0
var GameLoop = function() { 
    for(var i = 0, len = arrayOfGameObjects.length; i<len; i++) { 
     gameObject.draw(); 
    } 
}; 

查看http://jsfiddle.net/SdBcx/2/

的一些注意事项这方面的工作:

  • 这是不好的做法,对数组对象使用for(obj in array)。原因是,如果您将自定义函数添加到Array.prototype,自定义函数将出现在for循环中!我在这里写了一个这样的例子:http://jsfiddle.net/BUp6T/
  • 你可以看到我将arrayOfGameObjects.length保存在len变量中。这只发生一次,在循环执行之前。这比通常的解决方案快得多:for(var i = 0; i < arrayOfGameObjects.length; i++)每个单循环迭代检索数组长度。