node.js EventEmitter导致范围问题

当使用nodejs事件系统时,我遇到了一个恼人的问题。 如下面的代码所示,当侦听器捕获一个事件时,事件发射器对象在callback函数中拥有“this”而不是侦听器。

如果将callback放在侦听器的构造函数中,这不是一个大问题,因为除了指针“this”之外,还可以使用构造函数作用域中定义的其他variables,如“self”或“that”。

但是,如果将callback放在构造函数之外(如原型方法),则在我看来,没有办法获得侦听器的“this”。

不太确定是否有其他解决scheme。 另外,为什么nodejs事件发出使用发射器作为监听器的调用者安装有点困惑?

util = require('util'); EventEmitter = require('events').EventEmitter; var listener = function () { var pub = new publisher(); var self = this; pub.on('ok', function () { console.log('by listener constructor this: ', this instanceof listener); // output: by listener constructor this: false console.log('by listener constructor self: ', self instanceof listener); // output: by listener constructor this: true }) pub.on('ok', this.outside); } listener.prototype.outside = function () { console.log('by prototype listener this: ', this instanceof listener); // output: by prototype listener this: false // how to access to listener's this here? } var publisher = function () { var self = this; process.nextTick(function () { self.emit('ok'); }) } util.inherits(publisher, EventEmitter); var l = new listener(); 

尝试显式地将侦听器绑定到callback:

 pub.on('ok', this.outside.bind(this));