What is the difference between these two constructor patterns?

别说谁变了你拦得住时间么 提交于 2019-11-26 17:20:43

问题


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

vs

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

Is there something that the EventEmitter.call(this) does that is required?


回答1:


Is there something that the EventEmitter.call(this) does that is required?

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.

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.




回答2:


util.inherits grabs the entire parent prototype, but you lose the constructor. 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.



来源:https://stackoverflow.com/questions/22791368/what-is-the-difference-between-these-two-constructor-patterns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!