Node.js 原型鏈

2018-01-12 17:48 更新

util核心模塊(require(“utils"))提供了一個(gè)創(chuàng)建函數(shù)原型鏈。該函數(shù)稱為 inherits ,并采用一個(gè)子類繼之以父類。

var inherits = require("util").inherits; 
/*www.o2fo.com*/
function Car(n){
    this.name = n;
}
Car.prototype.drive= function (destination) { 
    console.log(this.name, "can drive to", destination); 
} 

function FlyingCar(name) { 
    // Call parent constructor 
    Car.call(this, name);
    // Additional construction code 
} 
inherits(FlyingCar, Car); 

// Additional member functions 
FlyingCar.prototype.fly = function (destination) { 
    console.log(this.name, "can fly to", destination); 
} 

var bird = new FlyingCar("XXX"); 
bird.drive("New York"); 
bird.fly("Seattle");

上面的代碼生成以下結(jié)果。

inherits函數(shù)結(jié)果

覆蓋子類中的函數(shù)

要覆蓋父函數(shù)但仍使用一些原始功能,只需執(zhí)行以下操作:

在子原型上創(chuàng)建一個(gè)具有相同名稱的函數(shù)。調(diào)用父函數(shù)類似于我們調(diào)用父構(gòu)造函數(shù)的方法,基本上使用

Parent.prototype.memberfunction.call(this, /*any original args*/) syntax. 
// www.o2fo.com
// util function 
var inherits = require("util").inherits; 
// Base 
function Base() { 
   this.message = "message"; 
}; 
Base.prototype.foo = function () { 
   return this.message + " base foo" 
}; 


// Child 
function Child() { Base.call(this); }; 
inherits(Child, Base); 

// Overide parent behaviour in child 
Child.prototype.foo = function () { 
    // Call base implementation + customize 
    return Base.prototype.foo.call(this) + " child foo"; 
} 

// Test: 
var child = new Child(); 
console.log(child.foo()); // message base foo child foo 

上面的代碼生成以下結(jié)果。

覆蓋結(jié)果


檢查繼承鏈

var inherits = require("util").inherits; 
/*from www.o2fo.com*/
function A() { } 
function B() { }; inherits(B, A); 
function C() { } 

var b = new B(); 
console.log(b instanceof B); // true because b.__proto__ == B.prototype 
console.log(b instanceof A); // true because b.__proto__.__proto__ == A.prototype 
console.log(b instanceof C); // false 

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)