I’m new to the way JavaScript scopes, so this is my problem:
"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";
}
This will throw the exception:
Uncaught TypeError: Cannot call method ‘drawImage’ of undefined
I know that this is due to the way JavaScript scopes, since ‘this’ now refers to the ‘_texture’ field.
As you can see Explorer (some kind of player-like object) inherits from GraphicsObject that in turn has a property graphics (the context of a canvas element).
I’ve found a way to fix this problem but in my opinion it’s a bit of a dirty one:
"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";
}
So all works as expected now, the image is neatly drawn onto the canvas element.
The only problem is that I now have another reference to ‘graphics’ I don’t really want.
So my question is:
Is there any way of making ‘this’ refer to the Explorer object, or forcing the scope to change?
thisis always local to the function, it’s evaluated every time a function is called depending on how the function is called. In this case the browser calls the function withthisset to the image object that_texturepoints to.Since normal variables are looked up from outer scope, you can simply save the old
thisto some variable: