util.inherits(constructor, superConstructor)
extends 关键字。constructor<Function>superConstructor<Function>
不推荐使用 util.inherits()。请使用 ES6 的 class 和 extends 关键字来获得语言级别的继承支持。同时请注意,这两种风格是 语义不兼容。
【Usage of util.inherits() is discouraged. Please use the ES6 class and
extends keywords to get language level inheritance support. Also note
that the two styles are semantically incompatible.】
将一个 function Object() [native code] 的原型方法继承到另一个中。constructor 的原型将被设置为由 superConstructor 创建的新对象。
【Inherit the prototype methods from one constructor into another. The
prototype of constructor will be set to a new object created from
superConstructor.】
这主要是在 Object.setPrototypeOf(constructor.prototype, superConstructor.prototype) 之上添加了一些输入验证。作为额外的便利,superConstructor 将可以通过 constructor.super_ 属性访问。
【This mainly adds some input validation on top of
Object.setPrototypeOf(constructor.prototype, superConstructor.prototype).
As an additional convenience, superConstructor will be accessible
through the constructor.super_ property.】
const util = require('node:util');
const EventEmitter = require('node: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); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('It works!'); // Received data: "It works!" 使用 class 和 extends 的 ES6 示例:
【ES6 example using class and extends:】
import EventEmitter from 'node:events';
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');const EventEmitter = require('node:events');
class MyStream extends EventEmitter {
write(data) {
this.emit('data', data);
}
}
const stream = new MyStream();
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
});
stream.write('With ES6');