Javascript初级 JavaScript进阶

JavaScript继承封装


示例代码


<html>

<head>

    <meta charset=”utf-8>

    <title></title>

</head>

<body>

<script type=”text/javascript”>

   Function shape(){};

   Shape.prototype.name=’shape’;

       Shape.prototype.tostring=function(){

          Var result=[];

          If(this.constructor.uber){

              Result[result.length]=this.constructor.uber.tostring();

          }

          Result[result.length]=this.name;

          Return result.join(‘,  ’)

      }

  

Function TwDSshape(){}

Var F=function(){}

F.prototype=Shape.prototype;

TwDSshape.prototype=new F()

TwDSshape.prototype.constuctor=TwDSshape;

TwDSshape.uber=Shape.prototype

TwDSshape.prototype.name=’2D Shape’;

 

Function triangle(side,height){

This.side=side;

This.height=height;

}

Var F=function(){};

F.prototype=TwDSshape.prototype;

Triangle.prototype=new F();

Triangle.prototype.constructor=triangle;

Triangle.unber=TwDSshape.prototype;

Triangle.prototype.name=’triangle’;

Triangle.prototype.gerarea=function(){

Return this.side*this.height/2

}

Var my=new triangle(5,10);

Console.log(my.getarea());

Console.log(my.tostring());

 

Var td=new TwDSshape();

Console.log(td.tostring());

        </script>

</body>

</html>


javascript2.png 

 

2、继承封装


示例代码


<html>

<head>

    <meta charset=”utf-8>

    <title></title>

</head>

<body>

<script type=”text/javascript”>

function extend(child,parent){

        var F=function(){};

F.prototype=parent.prototype;

Child.prototype=new F();

Child.prototype.constructor=Child;

Child.uber=parent.prototype;

}

Function shape(){};

   Shape.prototype.name=’shape’;

       Shape.prototype.tostring=function(){

          Var result=[];

          If(this.constructor.uber){

              Result[result.length]=this.constructor.uber.tostring();

          }

          Result[result.length]=this.name;

          Return result.join(‘,  ’)

      };

Function TwoDShape(){};

extend(TwoDShape,Shape);

TwoDShape.prototype.name=’2D Shape’;

 

function trinangle(side,height){

this.side=side;

this.height=height;

}

 

extend(Triangle,TwoDshape);

Triangle.prototype.name=’triangle’

Triangle.prototype.getArea=function(){

return this.side*this.height/2;

}

var my =new Triangle(5,10);

console.log(my.getArea());

console.log(my.toString());

 

var td =new TwoDShape();

console.log(td.toString());

 </script>

</body>

</html>

 

执行结果:


javascript1.png



【本文由麦子学院独家原创,转载请注明出处并保留原文链接】

logo
© 2012-2016 www.maiziedu.com
蜀ICP备13014270号-4 Version 5.0.0 release20160127

您有一个双11钜惠红包未领取

客服热线 400-862-8862

回到顶部