这两种构造函数模式有什么区别? [英] What is the difference between these two constructor patterns?

查看:38
本文介绍了这两种构造函数模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

对比

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

EventEmitter.call(this) 是否需要执行某些操作?

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?

显然,是的:

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;
};

因为所有使用 ._events 的方法都会检查它的存在,如果你确实省略了调用,我不希望有太多的破坏,但我不确定这是否适用于未来.

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.

这篇关于这两种构造函数模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆