constructor{Function}superConstructor{Function}
不建议使用 util.inherits()。
请使用 ES6 的 class 和 extends 关键词获得语言层面的继承支持。
这两种方式是[语义上不兼容的][semantically incompatible]。
从一个[构造函数][constructor]中继承原型方法到另一个。
constructor 的原型会被设置到一个从 superConstructor 创建的新对象上。
这主要在 Object.setPrototypeOf(constructor.prototype, superConstructor.prototype) 之上添加了一些输入验证。
作为额外的便利,可以通过 constructor.super_属性访问 superConstructor。
const util = require('util');const EventEmitter = require('events');function MyStream() {EventEmitter.call(this);}util.inherits(MyStream, EventEmitter);MyStream.prototype.write = function(data) {this.emit('data', data);};const stream = new MyStream();console.log(stream instanceof EventEmitter); // trueconsole.log(MyStream.super_ === EventEmitter); // truestream.on('data', (data) => {console.log(`接收的数据:"${data}"`);});stream.write('运作良好!'); // 接收的数据:"运作良好!"
使用 ES6 的 class 和 extends 的示例:
const EventEmitter = require('events');class MyStream extends EventEmitter {write(data) {this.emit('data', data);}}const stream = new MyStream();stream.on('data', (data) => {console.log(`接收的数据:"${data}"`);});stream.write('使用 ES6');
