//练习js继承(组合继承:原型继承和构造函数继承的组合)
function Polygon(length, area) {
    this.length = length;
    this.area = area;
}
Polygon.prototype = {
    constructor: Polygon,
    getLength: function () { console.log(this.length);console.log(" Polygon--getLength()!"); },
    getArea: function () { console.log(this.area); },
    sayHello: function () { console.log("Hi,I'm Polygon!");}
}
function Triangle(length, area) {
    //继承属性
    Polygon.call(this, length, area);//在子类对象上调用父类构造函数
   //添加新属性
   //this.a=a;

}
//继承方法
Triangle.prototype = new Polygon();
//注意:通过原型链实现继承时,不能使用对象字面量创建原型的方法,会导致重写原型链
/*Triangle.prototype = {
    constructor: Triangle,
    getLength: function () { console.log("Triangle length is " + this.length); },
    getArea: function () { console.log("Triangle area is " + this.area); }
}*/

Triangle.prototype.constructor = Triangle;//设置constructor属性
//重写父类方法
Triangle.prototype.getLength = function () {
    //Polygon.prototype.getLength.call(this);
    console.log("Triangle length is " + this.length);
};


Triangle.prototype.getArea = function () {
    console.log("Triangle area is " + this.area);
};
//添加新方法
Triangle.prototype.sayTriangle = function () { console.log("Hi,I'm Triangle!"); };


var polygon1 = new Polygon(1, 2);
polygon1.getLength();
polygon1.getArea();

var triangle1 = new Triangle(12, 16);

//调用子类重写的方法
triangle1.getLength();
triangle1.getArea();
//调用子类的新方法
triangle1.sayTriangle();
//调用父类未被重写的方法
triangle1.sayHello();
//调用父类被重写的方法
Polygon.prototype.getLength.call(triangle1);

console打印信息:

1
Polygon--getLength()!
2
Triangle length is 12
Triangle area is 16
Hi,I'm Triangle!
Hi,I'm Polygon!
12
Polygon--getLength()!

posted on 2017-06-01 09:44  Yogurshine  阅读(231)  评论(0编辑  收藏  举报