Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - What is the difference between these two constructor patterns?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...