【问题标题】:Uncaught TypeError: Cannot read property 'getContext' of undefined未捕获的类型错误:无法读取未定义的属性“getContext”
【发布时间】:2016-02-25 21:27:07
【问题描述】:

我在运行脚本时收到此错误“Uncaught TypeError: Cannot read property 'getContext' of undefined”。似乎变量“canvas”未定义,但我不知道为什么。

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();
    }
};

【问题讨论】:

  • 没关系,我想通了。我在世界文字之外声明了变量画布,现在它正在工作,但我仍然不明白为什么你不能在里面声明。
  • this 在 javascript 中非常奇怪。在您的情况下,如果您不想在世界之外添加变量,则必须执行 context: world.canvas.getContext("2d")

标签: javascript


【解决方案1】:

我在 world 文字之外声明了变量 canvas 并且它正在工作

【讨论】:

    【解决方案2】:

    对象字面量不会为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();
        }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2021-12-22
      • 2015-01-06
      • 2017-07-26
      • 2019-02-26
      相关资源
      最近更新 更多