http://developer.51cto.com/art/201103/248504_all.htm
3、组合构造函数/原型方式写类 ,采用前面种方式继承
这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上。
- * 父类Polygon:多边形
- function Polygon(sides) {
- this.sides = sides;
- Polygon.prototype.setSides = function(s) {this.sides=s;}
- * Triangle 三角形
- * @param {Object} base 底
- * @param {Object} height 高
- function Triangle(base,height) {
- Polygon.call(this,3);//复制父类属性给自己
- this.base = base;
- this.height = height;
- Triangle.prototype = new Polygon();//复制父类方法给自己
- Triangle.prototype.getArea = function(){ //最后定义自己的方法
- return this.base*this.height/2;
- //new个对象
- var tri = new Triangle(12,4);
- console.log(tri.sides);//继承的属性
- console.log(tri.setSides);//继承的方法
- console.log(tri.base);//自有属性
- console.log(tri.height);//自有属性
- console.log(tri.getArea);//自有方法
- //instanceof测试,表明正确的维护了"is a"的关系
- console.log(tri instanceof Triangle);//true,表明该对象是三角形
- console.log(tri instanceof Polygon);//true,表明三角形也是多边形
//可以用json方式简化prototype的定义:
Car.prototype =
{
color: "red",
doors: 4,
drivers: ["Tom", "Jerry",'safdad'],
showColor: function() {
alert(this.color);
}
}