search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

[Node.js] util 模組 – 原型物件繼承

此篇文章瀏覽量: 764

此篇文章介紹原型物件繼承的方法,將使用 util 模組的 util.inherits() 方法來實作原型物件繼承的功能。

原型物件繼承

使用 util.inherits() 繼承方法時,基礎類別 constructor 內部的屬性和方法均不會被子類別所繼承,只有透過原型方法建立的屬性和方法才會被子類別所繼承。

var util = require('util'); // 引入常用工具(util)模組

// 定義原型基礎類別 Base
function Base() {
  this.name = 'base';
  this.year = 2017;
  this.sayHello = function() {
    console.log('Hello ' + this.name + ',' + 'this is ' + this.year + '.');
  };
}

// 定義基礎類別 Base 的方法 showName()
Base.prototype.showName = function() {
  console.log(this.name);
};

// 定義基礎類別 Base 的方法 showYear()
Base.prototype.showYear = function() {
  console.log(this.year);
};

// 定義原型子類別 Child
function Child() {
  this.name = 'child';
}

// 使用 util.inherits(constructor, superConstructor) 方法實作原型物件繼承
util.inherits(Child, Base);

// 定義基礎類別 Base 物件
var objBase = new Base();
objBase.showName();
objBase.showYear();
objBase.sayHello();
console.log(objBase);

// 定義子類別 Child 物件
var objChild = new Child();
objChild.showName();
objChild.showYear();
//objChild.sayHello();
console.log(objChild);

輸出的結果如下圖:

若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。



熱門推薦

本文由 carlos-studiocom 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦