我是一种新的方式JavaScript的范围,所以这是我的问题:逃生JavaScript事件范围
"use strict";
function Explorer(xPos, yPos) {
// Inheritance
GraphicsEntity.call(this, {
x: xPos,
y: yPos,
width: 32,
height: 32
});
// Local fields
var _texture = new Image();
// Contruct
_texture.addEventListener("load", function() {
this.graphics.drawImage(_texture, 0, 0);
}, false);
_texture.src = "explorer.png";
}
这会抛出异常:遗漏的类型错误:无法调用未定义
法“的drawImage”我知道这是由于JavaScript范围的方式,因为'this'现在引用'_texture'字段。 正如你所看到的Explorer(某种类似玩家的对象)从GraphicsObject继承而来,GraphicsObject又有一个属性graphics(canvas元素的上下文)。
我已经找到一种方法来解决这个问题,但在我看来,这是一个有点脏之一:
"use strict";
function Explorer(xPos, yPos) {
// Inheritance
GraphicsEntity.call(this, {
x: xPos,
y: yPos,
width: 32,
height: 32
});
// Local fields
var _texture = new Image();
var _graphics = this.graphics;
// Contruct
_texture.addEventListener("load", function() {
_graphics.drawImage(_texture, 0, 0);
}, false);
_texture.src = "explorer.png";
}
因此,作为目前预计所有作品,图像被整齐地画在画布上的元素。 唯一的问题是,我现在有另一个参考'图形'我真的不想要。
所以我的问题是: 有没有什么办法让'this'引用Explorer对象,或者强制范围改变?
+1 - 就是这样 – 2011-12-20 16:19:09
所以基本上和我修正它的方式一样,但是使用对整个Object本身的引用?嗯......这可以工作。 – 2011-12-20 16:42:01
@JonKoops最好只使用整个对象,它只是一个引用,所以它不会占用更少或更多的内存(即使多个事物指向内存,对象在内存中仍然只有一种表示形式)。这样,当你在回调中需要比'explorer.graphics'更多的东西时,你不需要重写。 – Esailija 2011-12-20 16:48:31