Possible Duplicate:
JavaScript “this” keyword
I am a bit confused about the callbacks used for EventEmitter ‘s in node.js.
var events = require("events");
function myObject() {
this.name = "Test Object";
this.x = 99;
this.y = 100;
}
myObject.prototype = new events.EventEmitter();
var myobject = new myObject();
myobject.addListener('dbg1', function() {
console.log("this.name = " + this.name); //this.name gives the name not undefined
console.log("myobject.name = " + myobject.name); //so does this
});
myobject.emit('dbg1');
Why is this inside the callback referring to myobject? The closure for the callback function is the global scope in this code, am I right?
Scope is irrelevant for determining the value of
this, that comes from the context. That is determined by how the function is called. The events module you load will call it in the context ofmyobject.The relevant code is:
The first argument of the
applymethod is the context to use for calling the function (listener). You can trace it back to the object from there.