2016-02-25 74 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(); 
    } 
}; 
相关问题