第一種 prototype 引用型原型繼承
語(yǔ)言支持:js原生支持的繼承方式 構(gòu)造器的的prototype屬性作為類(lèi)的原型 每個(gè)該類(lèi)的對(duì)象都持有一個(gè)到原型的引用 當(dāng)對(duì)象中的屬性不存在時(shí) 可以訪問(wèn)原型的屬性
代碼示例:
<script>
function parent(){
    
this.x=10;
}
function child(){
}
child.prototype
=new parent();
var childObj=new child();
alert(childObj.x);
</script>
第二種 復(fù)制型原型繼承
語(yǔ)言支持:js new運(yùn)算符的性質(zhì) 當(dāng)構(gòu)造函數(shù)return值為非空對(duì)象時(shí) new表達(dá)式返回return的對(duì)象
代碼示例:
<script>
function parent(){
    
this.x=10;
}
function child(){
    
var ret=new parent();
    ret.y
=20;
    
return ret;
}

var childObj=new child();
alert(childObj.x);
</script>

第三種 類(lèi)繼承 屬性抄寫(xiě)
語(yǔ)言支持:for in枚舉對(duì)象所有屬性
代碼:

<script>
function parent(){
    
this.x=10;
}
function child(){
    
var parentObj=new parent();
    
for(var p in parentObj)this[p]=parentObj[p];
}
var childObj=new child();
alert(childObj.x);
</script>

第四種 類(lèi)繼承 對(duì)象冒充
語(yǔ)言支持: 1.動(dòng)態(tài)添加和刪除方法 2.函數(shù)的call和apply
代碼:
用語(yǔ)言支持1實(shí)現(xiàn)的類(lèi)繼承
<script>
function parent(){
    
this.x=10;
}
function child(){
    
this.parent=parent;
    
this.parent();
    
delete this.parent;
}
var childObj=new child();
alert(childObj.x);
</script>

用語(yǔ)言支持2實(shí)現(xiàn)的類(lèi)繼承

<script>
function parent(){
    
this.x=10;
}
function child(){
    parent.call(
this);
}
var childObj=new child();
alert(childObj.x);
</script>

第五種 原型抄寫(xiě)
語(yǔ)言支持:通過(guò)修改類(lèi)的原型對(duì)象 可以為一類(lèi)對(duì)象添加屬性和方法
代碼:

<script>
function parent(){}
parent.prototype.me
=function(){alert("parent")};
function child(){}
for(var p in parent.prototype)child.prototype[p]=parent.prototype[p];
var childObj=new child();
childObj.me();
</script>

第六種 元類(lèi)
語(yǔ)言支持: js函數(shù)都是對(duì)象 且js函數(shù)可被構(gòu)造
代碼:
<script>function parent(string){
    
var child=new Function("this.x=10;"+string);
    
return child;
}
var child=new parent("this.y=20;");

var childObj=new child();
alert(childObj.y);
</script>

以下通過(guò)混合構(gòu)造函數(shù)與原型方式來(lái)實(shí)現(xiàn)JS的繼承功能。 Polygon為父類(lèi),Triangle Rectangle 為子類(lèi)。

function Polygon (iSiders){
    
this.sides = iSiders;
}
Polygon.prototype.getArea 
= function(){
    
return 0;
}


function Triangle(iBase,iHeight){
    Polygon.call(
this,3);
    
this.base = iBase;
    
this.height = iHeight;
}
Triangle.prototype 
= new Polygon();
Triangle.prototype.getArea 
= function(){
    
return 0.5*this.base*this.height;
}

function Rectangle(iLength,iWidth){
    Polygon.call(
this,4);
    
this.length = iLength;
    
this.width = iWidth;
}
Rectangle.prototype 
= new Polygon();
Rectangle.prototype.getArea 
= function(){
    
return this.length*this.width;
}
var triangle = new Triangle(12,4);
var rectangle = new Rectangle(22,10);
alert(triangle.getArea);
alert(rectangle.getArea);

原文:http://blog.csdn.net/lenotang/archive/2008/08/27/2840315.aspx