簡體   English   中英

我收到錯誤Uncaught TypeError:無法讀取未定義的屬性'drawBox',有人可以發現問題嗎?

[英]I'm getting the error Uncaught TypeError: Cannot read property 'drawBox' of undefined, Can anyone spot the issue?

我是javascript新手,正在嘗試使用HTML 5畫布,我正在嘗試在屏幕上打印文本框,但似乎無法弄清問題所在。 我在Chrome瀏覽器javascript控制台中遇到的錯誤是“未捕獲的TypeError:無法讀取未定義的屬性'drawBox'”

var Box = Box || function(x, y, title, desc){
    Box.commonMethod.setup(x, y, title, desc);
};

function init(){
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "Black";
    ctx.fillRect(0,0,150,75);
    var b = new Box(10,10,'hello', 'this is text');
    b.commonMethod.drawBox(ctx);
}

Box.commonMethod = {

        locx: 25,
        locy: 25,
        desc: "",
        title: "",
        width: 100,
        height: 100,

  setup: function(x, y, title, description){
    this.locx = x;
    this.locy = y;
    this.title = title;
    this.desc = description;
  },

  drawBox: function(ctx){
      ctx.font = "15px Arial";
      ctx.fillRect(this.x,this.y, this.width+2, this.height);
      ctx.fillStyle = "White";
      ctx.fillRect(this.x+1,this.y+1, this.width, this.height-2);
      ctx.fillStyle = "black";
      ctx.fillText(this.title, this.x, this.y+15);
      ctx.fillText(this.desc, this.x, this.y+40);
  }

}

對象實例(在您的情況下為b )不會選擇附加到其構造函數的方法(在您的情況下為Box )。 但是他們選擇了構造函數原型上的方法。

定義對象實例的通用屬性/方法的正確方法是將它們定義為構造函數原型的一部分:

Box.prototype.commonMethod = { ...

如果進行此更改,則以下代碼行將起作用:

b.commonMethod.drawBox(ctx);

但是,然后,您還必須將構造函數調整為:

var Box = Box || function(x, y, title, desc){
    this.commonMethod.setup(x, y, title, desc);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM