通过原型循环的Javascript

Javascript looping through prototype

本文关键字:Javascript 循环 原型      更新时间:2023-09-26

请考虑代码:

// 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);
    }
};

然后我们可以实例化GameObject 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只是一个Index,那么如何执行draw((方法呢?该索引不包含任何对象。它只是一个索引,对吧?

这是一个链接

您真的应该为GameLoop:使用以下内容

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

使用普通的for循环迭代数组。

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

在数组上使用for in循环实际上是一种糟糕的做法,因为这只是获得所需索引的一种迂回方法。

我喜欢jquery$.each

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

否则,如其他人所述,使用进行,并使用数组长度进行迭代。

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

查看此工作http://jsfiddle.net/SdBcx/2/

一些注意事项:

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