【发布时间】:2012-01-24 14:01:22
【问题描述】:
我不熟悉 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(画布元素的上下文)。
我找到了解决这个问题的方法,但在我看来它有点脏:
"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 对象,或者强制改变范围?
【问题讨论】:
标签: javascript html scope html5-canvas dom-events