2016-02-25 100 views
1

我收到此錯誤「Uncaught TypeError:無法在運行腳本時讀取屬性'未定義的屬性'getContext'」。看起來變量「畫布」是未定義的,但我不明白爲什麼。Uncaught TypeError:無法讀取未定義的屬性'getContext'

var world = { 
    canvas: document.getElementById("myCanvas"), 
    context: this.canvas.getContext("2d"), 
    centerX: this.canvas.width/2, 
    centerY: this.canvas.height/2, 
    drawShape: function (shape) { 
     if (typeof shape.draw() === "function") 
      shape.draw(); 
    } 
}; 
+0

沒關係,我想通了。我在世界文字外面聲明瞭可變畫布,現在它正在工作,但我仍不明白爲什麼你不能在裏面聲明。 –

+0

'這'在JavaScript中非常奇怪。在你的情況下,你必須做 'context:world.canvas.getContext(「2d」)' 如果你不想在世界之外添加變量 –

回答

1

我宣佈world文字的可變canvas之外,它正在

0

對象文本不建立上下文this,所以你不能它的字面定義中引用一個對象作爲this

對於您的情況this.canvas.getContext可能被評估爲window.(undefined).getContext,因爲window沒有canvas屬性。

您可以保存到canvas屬性的引用,避免this

var world = { 
    canvas: (var canvas = document.getElementById("myCanvas")), 
    context: canvas.getContext("2d"), 
    centerX: canvas.width/2, 
    centerY: canvas.height/2, 
    drawShape: function (shape) { 
     if (typeof shape.draw() === "function") 
      shape.draw(); 
    } 
}; 
相關問題