2015-09-28 48 views
1

對於大學我必須做一個MVC風格編碼的JavaScript遊戲。 (模型,視圖,控制器)。我對此很新,所以請不要太難。我收到以下錯誤:「Uncaught TypeError:無法讀取未定義的屬性」getData「。有人可以幫我找出問題嗎?我敢肯定我的代碼充滿了錯誤。我試圖讓玩家模型在畫布上繪製。任何和所有的幫助,將不勝感激!這裏是我的代碼:爲什麼我的'getData'函數不能被我的代碼訪問?

var GOBLINS = GOBLINS || {}; 

GOBLINS.View = function() {}; 

GOBLINS.View.prototype.draw = function(objects) { 

    for(i=0; i < objects.length; i++) { 
      ctx.drawImage(objects[i],0,0); 
    }; 
}; 

GOBLINS.View.prototype.update = function(data){ 
    this.draw(data); 
}; 

GOBLINS.Model = function() { 
    this.data = []; 
}; 

GOBLINS.Model.prototype.player = { 
    hitPoints: 25, 
    x: 15, 
    y: 20, 
    img: new Image(), 
    push: function() { 
    data.push(GOBLINS.Model.player.img); 
    } 
}; 

GOBLINS.Model.prototype.getData = function(recall){ 
     recall(this.data); 
}; 

GOBLINS.Controller = function() { 
    var M = new GOBLINS.Model(); 
    var V = new GOBLINS.View(); 

    this.mainLoop(); 
}; 

GOBLINS.Controller.prototype.mainLoop = function() { 
    var self = this; 

    this.M.getData(function(data){ 
     self.V.update(data); 
    }); 

    window.requestAnimationFrame(function(){ 
     self.mainLoop(); 
    }); 
}; 

window.onload = function() { 
    var game = new GOBLINS.Controller(); 

    GOBLINS.Model.player.img.src = "Image/Player.png"; 
    var c=document.getElementById("gameCanvas"); 
    var ctx=c.getContext("2d"); 
}; 

回答

1

因爲MV不是的this一部分。它們在本地範圍內適用於控制器方法。

var M = new GOBLINS.Model(); 
var V = new GOBLINS.View(); 

應該

this.M = new GOBLINS.Model(); 
this.V = new GOBLINS.View(); 
+0

太謝謝你了。我錯誤地寫下了教師代碼。 –

相關問題