JS也玩面向对象
下面用JS简单实现了继承、抽象类和虚函数
1.draw.js
下面用JS简单实现了继承、抽象类和虚函数
1.draw.js
// add a static method for Object Object.extend=function(destination,source){ for(property in source){ destination[property]=source[property]; } return destination; } // add a method for all Object Object.prototype.extend=function(object){ return Object.extend.apply(this,[this,object]); } //this is the define of the base classs function baseShape(){} baseShape.prototype={ penWidth:'', penColor:'red', draw:function(){} } // sub class drw a line function line(penWidth,penColor){ this.penWidth=penWidth; this.penColor=penColor; } line.prototype=(new baseShape()).extend({ draw:function(){ alert("this pen can draw a line! "+"penWidth:"+this.penWidth+" penColor:"+this.penColor); } }); // sub class drw a rectangle function rectangle(penWidth,penColor){ this.penWidth=penWidth; this.penColor=penColor; } rectangle.prototype=(new baseShape()).extend({ draw:function(){ alert("this pen can draw a rectangle! "+"penWidth:"+this.penWidth+" penColor:"+this.penColor); } }); // sub class drw a circle function circle(penWidth,penColor){ this.penWidth=penWidth; this.penColor=penColor; } circle.prototype=(new baseShape()).extend({ draw:function(){ alert("this pen can draw a circle! "+"penWidth:"+this.penWidth+" penColor:"+this.penColor); } }); 2.页面shape.html<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>shape.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript" src="draw.js"> </script> <script language ="javascript" type="text/javascript"> function draw(){ var shape= form1.shape.value; var penWidth=form1.penWidth.value; var penColor=form1.penColor.value; var shape; if(shape=='line'){ shape=new line(penWidth,penColor); } if(shape=='rectangle'){ shape=new rectangle(penWidth,penColor); } if(shape=='circle'){ shape=new circle(penWidth,penColor); } shape.draw(); } </script> </head> <body> <form method="get" name="form1"> <table width="497" border="0" height="31"> <tbody><tr> <td>形状:</td> <td> <select name="shape"> <option value="line">直线</option> <option value="rectangle">矩形</option> <option value="circle">圆</option> </select> </td> <td>笔宽:</td> <td> <select name="penWidth"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </td> <td>笔色:</td> <td> <select name="penColor"> <option value="red">red</option> <option value="green">green</option> <option value="blue">blue</option> </select> </td> <td> <input type="button" value="draw" name="darw" οnclick="draw()"> </td> </tbody></table> </form> </body> </html>