Zi 字媒體
2017-07-25T20:27:27+00:00
此篇文章瀏覽量:
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);
輸出的結果如下圖:
若覺得文章有幫助,請多分享,讓其他同好也能吸收網站技能知識。
Facebook
Twitter
寫了
5860316篇文章,獲得
23313次喜歡