I am attempting to use the method invocation pattern in Javascript. I declare a function as an object member.
According to Javascript: The Good Parts, this should result in the this
pointer referencing the enclosing object. When I've tried this before, this has been the case.
In the sample of code below, the this
pointer reference by the single console.log
statement is pointing to the function, not the object. I've double-checked my code and I honestly don't know what's going on.
I could use another pair of eyes on this. Is there something really obvious that I'm missing here, or am I expecting the wrong behavior? Thank you.
EDIT: I had a mistake in my code that I posted (it's been in flux); the keyword inside the anonymous function should be that
, not this
. Fixed.
DOUBLE EDIT: I've added the rest of my code within the module. I'm trying to write a commonJS module (in accordance with the gameJS library that I'm using) and although I'm not sure where that would be the problem, I'm wondering if it is. Does this change anything?
var gamejs = require('gamejs');
var system = require('app/system');
var input = {
eval_keys: function () {
console.log(this); // This should be the outer object, but shows the function!
var that = this;
gamejs.event.get().forEach(function (event) {
if (event.type === gamejs.event.KEY_DOWN) {
for (var key in that.keyconfig) {
if (that.keyconfig.hasOwnProperty(key)) {
if (event.key === gamejs.event[key]) {
that.keyconfig.key = true;
}
}
}
system.log("KEYDOWN", event.key);
}
if (event.type === gamejs.event.KEY_UP) {
for (var key in that.keyconfig) {
if (that.keyconfig.hasOwnProperty(key)) {
if (event.key === gamejs.event[key]) {
that.keyconfig.key = false;
}
}
}
system.log("KEYUP", event.key);
}
return keyconfig;
});
},
eval_mouse: function () {
/* in progress
else if (event.type === gamejs.event.MOUSE_MOTION) {
// if mouse is over display surface
if (display.rect.collidePoint(event.pos)) {
system.log("mousemove", testcoords);
testcoords = event.pos;
}
}
*/
},
keyconfig: {
K_UP: false,
K_LEFT: false,
K_RIGHT: false,
K_DOWN: false
}
};
exports.eval_keys = input.eval_keys;
Output from Chrome's dev console:
Object {eval_keys: function}
eval_keys: function () {
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
__proto__: Object