有人能解释一下util.inherits在更多的外行人术语中做了什么吗?

时间:2014-01-26 02:18:16

标签: javascript node.js inheritance prototype prototypal-inheritance

http://nodejs.org/docs/latest/api/util.html#util_util_inherits_constructor_superconstructor

在上面的文档中,他们讨论了util.inherits,它需要两个构造函数。我试图围绕他们提供的代码示例包围我的大脑。我知道Stream是什么,我知道EventEmitter是什么,我理解为什么你想要从EventEmitter继承流,但我真的很困惑他们是怎样的'这样做。

util.inherits到底在做什么?为什么他们创建一个调用events.EventEmitter.call(this);的新构造函数?这种奇怪的做事方式与创建EventEmitter的新实例并将其设置为MyStream.prototype之间有什么区别?

以下是文章中的代码示例:

var util = require("util");
var events = require("events");

function MyStream() {
    events.EventEmitter.call(this);
}

util.inherits(MyStream, events.EventEmitter);

MyStream.prototype.write = function(data) {
    this.emit("data", data);
}

var stream = new MyStream();

console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true

stream.on("data", function(data) {
    console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"

2 个答案:

答案 0 :(得分:4)

...
s = ctx.socket( zmq.DEALER )

s.setsockopt( zmq.LINGER,    0 ) # ALWAYS, no excuse, you never know the peers' versions
s.setsockopt( zmq.IMMEDIATE, 1 ) # prevent sending over incomplete yet connections
s.setsockopt( zmq.CONFLATE,  1 ) # Does not support multi-part, so .pack() payload

s.connect( "tcp://localhost:5555" )
...

答案 1 :(得分:2)

您可以找到util.inherits here的实施方式:

exports.inherits = function(ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
};

它基本上正在执行您所描述的内容(创建events.EventEmitter.prototype的实例并将其设置为MyStream的原型)以及将events.EventEmitter附加到MyStream.super_

events.EventEmitter.call(this);调用events.EventEmitter构造函数,以便在创建新MyStream时执行它。这相当于在Java等其他语言中调用super()