Node.js中的子类模块;JavaScript(没有辅助工具)

Subclassing Modules in Node.js & JavaScript (without helper utilities)

本文关键字:辅助工具 JavaScript js 子类 模块 Node      更新时间:2023-09-26

我正在尝试寻找一些替代方法,以便对节点的EventEmitter 进行"子类化"

这就是我迄今为止使用es6/2015风格原型继承所做的工作。它运行良好,可读性强(IMO)。

class Emitter extends EventEmitter {
  // Hoping to augment #on() to accept a scope argument
  on(evt, cb, thisArg) {
    thisArg = thisArg ? thisArg : this;
    // This is the area I'm having trouble replicating w/ ES5
    return super.on.call(thisArg, evt, cb);
  } 
}
module.exports = Emitter;

除了使用新的ES6做事方式之外,我希望能想出一些其他方法来进行EventEmitter的子类化或扩展,这样我就可以更好地理解潜在的机制。我习惯于使用Object.create(proto)来设置原型链,但我在重写.on()方法而不导致堆栈溢出时遇到了问题。

我希望使用thisArg让用户设置回调的上下文。

到目前为止,我使用ES5方法得到的是:

let Emitter = Object.create(EventEmitter);
Emitter.on = function on(evt, cb, thisArg) {
  thisArg = thisArg ? thisArg : this;
  return this.on.call(thisArg, evt, cb);
};
module.exports = Emitter;

有什么想法吗?我知道你可以使用utils.inherits(),但我更想知道如何在没有任何"魔法"或辅助工具的情况下实现这一点。

首先让我们修复您的ES6代码。对于你想要实现的目标,你应该使用

return super.on(evt, cb.bind(thisArg));

而不是在CCD_ 6方法上调用CCD_。


在ES5中,您将使用标准方法编写此继承:

function Emitter() {
  EventEmitter.apply(this, arguments);
}
// these two lines could be `utils.inherit(Emitter, EventEmitter);`
Emitter.prototype = Object.create(EventEmitter.prototype);
Emitter.prototype.constructor = Emitter;
Emitter.prototype.on = function(evt, cb, thisArg) {
  thisArg = thisArg ? thisArg : this;
  return EventEmitter.prototype.on.call(this, evt, cb.bind(thisArg));
};
module.exports = Emitter;

对于您遇到问题的部分,这一切都是关于手动解析super引用以访问要调用的父方法。