简体   繁体   English

这两种构造器模式有什么区别?

[英]What is the difference between these two constructor patterns?

Function ConstrA () {
    EventEmitter.call(this);
}
util.inherits(ConstrA, EventEmitter);

vs VS

Function ConstrA() {}
util.inherits(ConstrA, EventEmitter);

Is there something that the EventEmitter.call(this) does that is required? 是否有EventEmitter.call(this)所需的功能?

Is there something that the EventEmitter.call(this) does that is required? 是否有EventEmitter.call(this)所需的功能?

Apparently , yes: 显然 ,是的:

function EventEmitter() {
  EventEmitter.init.call(this);
}
…

EventEmitter.init = function() {
  this.domain = null;
  if (EventEmitter.usingDomains) {
    // if there is an active domain, then attach to it.
    domain = domain || require('domain');
    if (domain.active && !(this instanceof domain.Domain)) {
      this.domain = domain.active;
    }
  }
  this._events = this._events || {};
  this._maxListeners = this._maxListeners || undefined;
};

Since all the methods that use ._events do a check for its existence I wouldn't expect much to break if you did omit the call, but I'm not sure whether this holds true in the future. 由于所有使用._events的方法都会检查它的存在,因此,如果您确实忽略了调用,我希望不会有太大的改变,但是我不确定将来是否成立。

There are enough other constructors that do not tolerate to be omitted, so it's good practice to simply always call the constructor when constructing an instance. 有迹象表明, 容忍省略了足够的其他构造函数,所以这是很好的做法,构造一个实例时只需随时调用构造函数。

util.inherits grabs the entire parent prototype, but you lose the constructor. util.inherits获取整个父级原型,但是会丢失构造函数。 For this reason, the inheriting constructor will often call the parent constructor with the current this as the context, just like you see in your first example. 因此,继承构造器通常会以当前this作为上下文来调用父构造器,就像您在第一个示例中看到的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM