コードを検討してください:
// 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 個のゲームオブジェクトの配列ができました。これらはすべて同じプロトタイプと draw メソッドの定義を共有しているため、アプリケーション内のメモリが大幅に節約されます。
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() メソッドを実行するにはどうすればよいでしょうか? そのインデックスはオブジェクトを保持しません。単なる指標ですよね?
ここにリンクがあります