2013-01-13 99 views
0

那麼問題出在遊戲的rects實例上:[],它應該是Rect對象的數組。當我訪問遊戲內的rects屬性時給出了未定義的內容。無法修改原型陣列內部

http://jsbin.com/ibilec/34/edit

(function(window, document, console) { 
    'use strict'; 

    function Rect() { 
    this.x = 0; 
    this.y = 0; 
    this.width = 20; 
    this.height = 20; 
    } 

    Rect.prototype.draw = function(ctx) { 
    ctx.fillRect(this.x, this.y, this.width, this.height); 
    }; 


    var Game = Object.create({  
    rects: [], /// PROBLEM IS WITH this 

    draw: function() { 
     console.log('Draw called', this.rects); 
     if (this.rects) { 
     this.rects.forEach(function(rect, index) { 
      console.log(rect); 
      rect.draw(this.ctx); 
     }); 
     } 

     //window.setInterval(function() { this.ctx.clearRect(0, 0, 200, 200); }, 1000); 


    }, 

    genRect: function() { 
     var newRect = new Rect(); 
     newRect.x = parseInt(Math.random() * 200, 10); 
     newRect.y = parseInt(Math.random() * 200, 10); 

     this.rects.push(newRect); 
    }, 

    loop: function() { 
     //Game.draw(); 
     // Frame rate about 30 FPS 

     window.setInterval(this.draw, 1000/30); 
    }, 

    init: function() { 
     this.canvas = document.getElementById('game'); 
     this.height = this.canvas.height; 
     this.width = this.canvas.width; 

     window.ctx = this.canvas.getContext('2d'); 


     this.genRect(); 
     this.loop(); //start loop 
    } 
    }); 

    var game = Object.create(Game); 
    game.init(); 
})(window, document, console); 

回答

2

draw方法不叫爲對象的方法,這就是所謂的在全球範圍內的功能,所以this將是window一個參考,而不是遊戲對象。

複印this給一個變量,並用它來從函數調用的方法:

var t = this; 
window.setInterval(function() { t.draw(); }, 1000/30); 
+0

這條線'rect.draw(this.ctx);'也是不正確的,因爲* * CTX保存到這裏的全局範圍'window.ctx = this.canvas.getContext('2d');' –

+0

@PeterPajchl:但是這個代碼是在一個回調函數內運行的,所以'this'就是'window'對象。 – Guffa

+0

哪個回調?你的答案中的一個? –