javacript实现类继承的几种方法

1 <scripttype="text/javascript">

  2//------------------对象冒充实现继承-----------------

  3 function ClassA(sColor)

  4 {

    this.color=sColor;

    this.showColor=function()

    {

        alert(this.color);

    }

 10 }

 11 function ClassC(iBig)

 12 {

 13    this.color=iBig;

 14    this.showBig=function()

 15    {

 16        alert(this.color);

 17    }

 18

 19 }

 20 function ClassB(sColor,sName,iBig)

 21 {

 22    this.newMethed=ClassA;

 23    this.newMethed(sColor);

 24    delete this.newMethed;

 25

 26    this.newMethed=ClassC;

 27    this.newMethed(iBig);

 28    delete this.newMethed;

 29

 30    this.name=sName;

 31    this.sayName=function()

 32    {

 33        alert(this.name);

 34    }

 35 }

 36 //var oCarA=new ClassA("red");

 37 //oCarA.showColor();

 38 var oCarB=newClassB("blue","myTest",100);

 39 oCarB.showColor();

 40 oCarB.showBig();

 41 oCarB.sayName();

 42//----------------call或apply方法实现继承---------------------

 43 function ClassA(sColor)

 44 {

 45    this.color=sColor;

 46    this.showColor=function()

 47    {

 48        alert(this.color);

 49    }

 50 }

 51 function ClassB(sColor,sName)

 52 {

 53    //this.newMethed=ClassA;

 54    //this.newMethed(sColor);

 55    //delete this.newMethed;

 56    //ClassA.call(this,sColor);

 57    //ClassA.apply(this,new Array(sColor));

 58    ClassA.apply(this,arguments);

 59

 60    this.name=sName;

 61    this.sayName=function()

 62    {

 63        alert(this.name);

 64    }

 65 }

 66 var oCarB=new ClassB("blue","myTest");

 67 oCarB.showColor();

 68 oCarB.sayName();

 69//-------------------原型链实现继承------------------------

 70 function ClassA(){}

 71 ClassA.prototype.color="red";

 72 ClassA.prototype.showColor=function()

 73 {

 74    alert(this.color);

 75 }

 76 }

 77 function ClassB(){}

 78

 79 ClassB.prototype=new ClassA();

 80 ClassB.prototype.name="smatt";

 81 ClassB.prototype.showName=function()

 82 {

 83    alert(this.name);

 84 }

 85 var oCar=new ClassB();

 86 oCar.showColor();

 87 oCar.showName();

 88//----------------------混合方式实现继承-----------------------------

 89 function ClassA(sColor)

 90 {

 91    this.color=sColor;

 92 }

 93 ClassA.prototype.showColor=function()

 94 {

 95    alert(this.color);

 96 }

 97 function ClassB(sColor,sName)

 98 {

 99    ClassA.call(this,sColor);

100    this.name=sName;

101 }

102 ClassB.prototype=new ClassA();

103 ClassB.prototype.showName=function()

104 {

105    alert(this.name);

106 }

107 var oCar=new ClassB("red","smatt");

108 oCar.showColor();

109 oCar.showName();

110    

111 </script>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值