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 of myobject.
The relevant code is:
listener.apply(this, args);
The first argument of the apply method is the context to use for calling the function (listener). You can trace it back to the object from there.
This is the same for most of the node codebase. There was a small discussion about this a long time ago, and the consensus was that .call(this) entails too much overhead and was really ugly/annoying to put everywhere. So in other words, don't ever assume this is what you think.
edit: Nevermind, EventEmitter doesn't specifically apply in this case and I completely misread your question.