Node.js – util.inherits() 方法
util.inherits() 方法实质上将方法从一个构造函数继承到另一个。此原型将设置为一个新对象,该对象来自 superConstructor。
通过此方法,我们可以主要在 Object.setPrototypeOf(constructor.prototype, superConstructor.prototype) 的顶部添加一些验证。
语法
util.inherits(constructor, superConstructor)
参数
以下是对这些参数的描述 -
- constructor − 这是输入函数类型,保存用户希望继承的构造函数的原型。
- superConstructor − 这是将用于添加和验证输入验证的函数。
示例 1
创建一个文件 "inherits.js",并复制以下代码段。创建文件后,使用命令 "node inherits.js" 运行此代码。
// util.inherit() example
// Importing the util module
const util = require('util');
const EventEmitter = require('events');
// Defining the constructor below
function Stream() {
EventEmitter.call(this);
}
// Inheriting the stream constructor
util.inherits(Stream, EventEmitter);
// Creating the prototype for the constructor with some data
Stream.prototype.write = function(data) {
this.emit('data', data);
};
// Creating a new stream constructor
const stream = new Stream();
// Checking if stream is instanceOf EventEmitter
console.log(stream instanceof EventEmitter); // true
console.log(Stream.super_ === EventEmitter); // true
// Printing the data
stream.on('data', (data) => {
console.log(`Data Received: "${data}"`);
});
// Passing the data in stream
stream.write('Its working... Created the constructor prototype!');输出
C:\home
ode>> node inherits.js true true Dta Received: "It's working... Created the constructor prototype!"
示例 2
我们再来看看另一个示例
// util.inherits() example
// Importing the util & events module
const util = require('util');
const { inspect } = require('util');
const emitEvent = require('events');
// Definging the class to emit stream data
class streamData extends emitEvent {
write(stream_data) {
// This will emit the data stream
this.emit('stream_data', stream_data);
}
}
// Creating a new instance of the stream
const manageStream = new streamData('default');
console.log("1.", inspect(manageStream, false, 0, true))
console.log("2.", streamData)
manageStream.on('stream_data', (stream_data) => {
// Prints the write statement after streaming
console.log("3.", `Data Stream Received: "${stream_data}"`);
});
// Write on console
manageStream.write('Inheriting the constructor & checking from superConstructor');输出
C:\home
ode>> node inherits.js 1. streamData { _events: [Object: null prototype] {}, _eventsCount: 0, _maxListeners: undefined, [Symbol(kCapture)]: false } 2. [class streamData extends EventEmitter] 3. Data Stream Received: "Inheriting the constructor & checking from superConstructor"
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP