0

コードを検討してください:

// 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() メソッドを実行するにはどうすればよいでしょうか? そのインデックスはオブジェクトを保持しません。単なる指標ですよね?

ここにリンクがあります

4

4 に答える 4

1

あなたは本当にあなたのために以下を使うべきですGameLoop:

var GameLoop = function() {
    for(var i = 0; i < arrayOfGameObjects.length; i++) {
        arrayOfGameObjects[i].draw();
    }
};
于 2013-04-03T08:06:39.513 に答える
0

単純なforループを使用して、配列を反復処理します。

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

for in配列でループを使用するのは実際には悪い習慣です。これは、必要なインデックスを取得するためのラウンド アバウトな方法に過ぎないためです。

于 2013-04-03T08:06:58.513 に答える