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"

更新於:16-8-2021

411 次瀏覽

開啟你的職業生涯

完成課程,獲得認證

開始
廣告