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");
上面的代码生成以下结果。
覆盖子类中的函数
要覆盖父函数但仍使用一些原始功能,只需执行以下操作:
在子原型上创建一个具有相同名称的函数。调用父函数类似于我们调用父构造函数的方法,基本上使用
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.ancii.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