codecamp

Node.js 原型链

util核心模块(require(“utils"))提供了一个创建函数原型链。该函数称为 inherits ,并采用一个子类继之以父类。

var inherits = require("util").inherits; 
/*www.w3cschool.cn*/
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");

上面的代码生成以下结果。

inherits函数结果

覆盖子类中的函数

要覆盖父函数但仍使用一些原始功能,只需执行以下操作:

在子原型上创建一个具有相同名称的函数。调用父函数类似于我们调用父构造函数的方法,基本上使用

Parent.prototype.memberfunction.call(this, /*any original args*/) syntax. 
// www.w3cschool.cn
// 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 

上面的代码生成以下结果。

覆盖结果


检查继承链

var inherits = require("util").inherits; 
/*from www.w3cschool.cn*/
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 

Node.js 类的创建
Node.js 错误和异常
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }