如何从函数访问类的成员变量

时间:2019-06-13 12:44:02

标签: node.js

我有两个班级

第1-

var dict = {};
class EventManager {
  constructor() {}

  subscribeForEvents(subscriber) {
    var emitter = null;
    if (dict.hasOwnProperty(subscriber.url)) {
      emitter = dict[subscriber.url];
    } else {
      emitter = new EventEmitter();
      dict[subscriber.url] = emitter;
    }
    emitter.on(subscriber.url, subscriber.onMessage);
    console.log("Number of listerner", emitter.listenerCount());
  }

  sendMessage(url,msg ){
    var emitter = dict[url];
    emitter.emit(url, msg);
  }
}

第2类

class Subscriber {
  constructor(url) {
    this.url = url;
    this.onMessage = function(data) {
      console.log(this);
      console.log(this.url);
    };
}
}

这是我在nodejs的第三个文件中使用这两个类的方式

const EventManager = require("./eventManager");
const eventManager = new EventManager();
const Subscriber = require("./eventSubscriber");
const eventSubscriber = new Subscriber("some_url");
eventManager.subscribeForEvents(eventSubscriber);

eventManager.sendMessage("some_url", {some : data});

现在当 sendMessage 触发 emit 函数时,在上面的代码上运行, onMessage 被调用,但 console.log(this)给我

EventEmitter {
  domain: null,
  _events: { 'incoming_call_updates/0712fa33-63ba-11e6-b56f-066beb27a027/konnect': [Function] },
  _eventsCount: 1,
  _maxListeners: undefined }

这不是 Subscriber 类的实例,因此 this.url 给了我未定义

如何访问订户中设置的对象/变量 emitter.on(subscriber.url, subscriber .onMessage);

0 个答案:

没有答案