js继承

本文介绍了一种JavaScript中实现继承的方法——组合继承,并通过具体实例展示了如何结合构造函数继承和原型链继承来实现属性和方法的有效传递。文章还讨论了如何在子类中重写父类方法及添加新方法。
//练习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()!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值