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