Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未捕获类型错误:无法读取属性';getContext';未定义的_Javascript - Fatal编程技术网

Javascript 未捕获类型错误:无法读取属性';getContext';未定义的

Javascript 未捕获类型错误:无法读取属性';getContext';未定义的,javascript,Javascript,在运行脚本时,我遇到以下错误“UncaughtTypeError:无法读取未定义的属性'getContext'。看起来变量“canvas”没有定义,但我不明白为什么 var world = { canvas: document.getElementById("myCanvas"), context: this.canvas.getContext("2d"), centerX: this.canvas.width / 2, centerY: this.canvas.

在运行脚本时,我遇到以下错误“UncaughtTypeError:无法读取未定义的属性'getContext'。看起来变量“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();
    }
};

我在
world
literal之外声明了变量
canvas
,它正在工作

一个对象literal没有为其建立上下文,因此您不能在其literal定义中将一个对象称为
this

在您的例子中,
this.canvas.getContext
可能被评估为
window.(未定义).getContext
,因为
window
没有
canvas
属性

您可以保存对
画布
属性的引用,并避免

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

没关系,我明白了。我在world literal之外声明了variable canvas,现在它可以工作了,但我仍然不明白为什么不能在内部声明。
这在javascript中非常奇怪。在您的情况下,如果不想在世界之外添加变量,您必须执行
context:world.canvas.getContext(“2d”)