为什么不能'我'getData'函数可以被我的代码访问

Why can't my 'getData' function be accessed by my code?

本文关键字:我的 代码 访问 getData 不能 为什么 函数      更新时间:2023-09-26

对于大学,我必须使用MVC风格编码制作javascript游戏。(模型,视图,控制器)。我是新手,所以请不要太难。我得到以下错误:"未捕获的类型错误:无法读取未定义的属性'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");
};

因为MV不是this的一部分。它们的局部作用域是controller方法。

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

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