I am looking at the implementation of once() in event.js:
EventEmitter.prototype.once = function(type, listener) {
if ('function' !== typeof listener) {
throw new Error('.once only takes instances of Function');
}
var self = this;
function g() {
self.removeListener(type, g);
listener.apply(this, arguments);
};
g.listener = listener;
self.on(type, g);
return this;
};
Remembering that you would do some_object.once('on', function(){ console.log(this); } );
The temporary function g() has self.removeListener(type,g)
. I assume that's because the context in g() would be wrong otherwise. But then, the line after that, the variable this
is used in listener.apply(this, arguments);
But... isn't this then passing the global context to listener(arguments)?
Then a little down, it runs self.on
instead if this.on
.
Now... I am confused. I am fairly new to Javascript, and I still get confused with the context. But, this code is driving me bananas... can somebody please enlighten me here?
Thanks,
Merc.