我是一種新的方式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