Possible Duplicate:
Javascript: Do I need to put this.var for every variable in an object?
我在使用以下代码时遇到了问题:
var BuildMiniMap = function(camera, mapSize, width){
this.camera = camera;
this.canvas = document.getElementById('gameCanvas');
this.mapSize = mapSize;
this.width = width;
this.height = Math.floor(mapSize[1]/(mapSize[0]/width));
alert(canvas);
}
var miniMap = new BuildMiniMap(camera, [800, 600], 200);
在网页中运行它会导致控制台出错:
Uncaught ReferenceError: canvas is not defined
我必须使用 this.canvas
反而。这只发生在 canvas
上属性(property),但不是任何其他属性(property)。有谁知道原因并可以提供解释吗?谢谢!
最佳答案
其他三个属性,camera
、mapSize
和 width
都定义为函数参数,因此在函数作用域内可用。 canvas
不是函数参数,也没有在函数内部定义,因此它不存在于作用域内。
关于javascript - 为什么我必须使用 this.canvas?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14251031/