通过原型循环的Javascript
Javascript looping through prototype
请考虑代码:
// 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++)
,后者在每次循环迭代中检索数组长度
相关文章:
- Javascript循环不会自我更新
- JavaScript循环无法正确计算/显示结果
- JavaScript循环并等待函数
- Javascript:循环属性内部的条件递增或递减
- Array方法中的Javascript循环
- 用于使用javascript循环选择选项
- 中断javascript循环
- 如何在javascript循环中打印代码
- jQuery.ajax()访问javascript循环中的beforeEnd局部变量
- 在qualtrics上使用javascript:循环块中的问题id
- GoogleMapsV3api只显示Javascript循环中的一些标记
- Javascript循环限制为仅1
- 如何将jQueryeach()转换为常规的javascript循环
- 有没有javascript循环的替代方案
- GraphQL代码中的Javascript循环依赖关系
- Javascript循环文本
- JavaScript循环中的HTML
- ..的Javascript..循环中的对象没有在最后一个属性上运行
- JavaScript循环迭代太多
- Javascript循环计算