js模擬類繼承小例子
更新時間:2010年07月17日 18:49:17 作者:
使用js模擬類繼承小例子,學(xué)習(xí)js面向?qū)ο蟮呐笥芽梢詤⒖枷隆?/div>
//使用原型繼承,中間使用臨時對象作為Child的原型屬性,臨時對象的原型屬性再指向父類的原型,
//防止所有子類和父類原型屬性都指向通一個對象.
//這樣當(dāng)修改子類的原型屬性,就不會影響其他子類和父類
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}
function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;}; //使用閉包模擬私有成員
this.setName = function(value){name=value;};
}
Parent.prototype.print = function(){alert("print!");};
Parent.prototype.hello = function()
{
alert(this.getName() + "Parent")
};
function Child(name,age)
{
Parent.apply(this, arguments);//調(diào)用父類構(gòu)造函數(shù)來繼承父類定義的屬性
this.age = age;
}
extend(Child,Parent); //繼承Parent
Child.prototype.hello = function() //重寫父類hello方法
{
alert(this.getName() + "Child");
Parent.prototype.hello.apply(this,arguments); //調(diào)用父類同名方法
};
//子類方法
Child.prototype.doSomething = function(){ alert(this.age + "Child doSomething"); };
var p1 = new Child("xhan",22);
var p2 = new Child("xxx",33);
p1.hello();
p2.hello();
p1.doSomething(); //子類方法
p1.print(); //父類方法
alert(p1 instanceof Child); //true
alert(p1 instanceof Parent);//true
復(fù)制代碼 代碼如下:
//使用原型繼承,中間使用臨時對象作為Child的原型屬性,臨時對象的原型屬性再指向父類的原型,
//防止所有子類和父類原型屬性都指向通一個對象.
//這樣當(dāng)修改子類的原型屬性,就不會影響其他子類和父類
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}
function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;}; //使用閉包模擬私有成員
this.setName = function(value){name=value;};
}
Parent.prototype.print = function(){alert("print!");};
Parent.prototype.hello = function()
{
alert(this.getName() + "Parent")
};
function Child(name,age)
{
Parent.apply(this, arguments);//調(diào)用父類構(gòu)造函數(shù)來繼承父類定義的屬性
this.age = age;
}
extend(Child,Parent); //繼承Parent
Child.prototype.hello = function() //重寫父類hello方法
{
alert(this.getName() + "Child");
Parent.prototype.hello.apply(this,arguments); //調(diào)用父類同名方法
};
//子類方法
Child.prototype.doSomething = function(){ alert(this.age + "Child doSomething"); };
var p1 = new Child("xhan",22);
var p2 = new Child("xxx",33);
p1.hello();
p2.hello();
p1.doSomething(); //子類方法
p1.print(); //父類方法
alert(p1 instanceof Child); //true
alert(p1 instanceof Parent);//true
相關(guān)文章
javascript Prototype 對象擴(kuò)展
從對象創(chuàng)建一個實(shí)例說起來貌似是很簡單的東西,是啊,基本在所有的語言中,都是用new關(guān)鍵字來創(chuàng)建實(shí)例的2009-05-05
ES6的異步操作之promise用法和async函數(shù)的具體使用
這篇文章主要介紹了ES6的異步操作之promise用法和async函數(shù)的具體使用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
JavaScript類的繼承操作實(shí)例總結(jié)
這篇文章主要介紹了JavaScript類的繼承操作,結(jié)合實(shí)例形式總結(jié)分析了JavaScript面向?qū)ο蟪绦蛟O(shè)計(jì)中類的繼承常見實(shí)現(xiàn)方式與操作技巧,需要的朋友可以參考下2018-12-12
起點(diǎn)頁面?zhèn)髦礿s,有空研究學(xué)習(xí)下
起點(diǎn)上的頁面?zhèn)髦礿s,有空研究下2010-01-01

