今天开始学习js,看到了js继承的方式.记录下来:
利用对象的call方法对父类进行初始化:下面用经典的图形例子来说明:
先定义一个形状Polygon
js 代码
- function Polygon(iSides) {
- this.sides = iSides;
- }
-
- Polygon.prototype.getArea = function() {
- return 0;
- }
下面定义两个子类,一个三角形Triangle,一个矩形Rectangle:
三角形;
js 代码
- 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;
- }
矩形:
js 代码
- function Rectangle(iLenght,iWidth) {
- Polygon.call(this,4);
- this.length = iLenght;
- this.width = iWidth;
- }
-
- Rectangle.prototype = new Polygon();
-
- Rectangle.prototype.getArea = function() {
- return this.length * this.width;
- }
测试一下:
js 代码
- function testFunc() {
- var triangle = new Triangle(12,4);
- var rectangle = new Rectangle(22,10);
-
-
- alert("[ " +triangle.sides + " : " + triangle.getArea() + " ][ " + rectangle.sides + " : " + rectangle.getArea() + " ]");
-
- }
新建一个html界面进行调用,用于本js是定义到一个单独的js文件中,需要在html中引入此js文件
js 代码
- <script type=< span="">"text/javascript" src="test.js"></script>
运行结果为:
见附件图面...