W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
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é)果。
要覆蓋父函數(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é)果。
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
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: