JS继承

示例
<script>
//constructor
function Shape(){}
//augment(扩展) prototype
Shape.prototype.name='Shape';
Shape.prototype.toString= function () {
return this.name;
}
//another constructor
function TwoDShape(){}
//take care of inheritance 构建继承关系
TwoDShape.prototype=new Shape();
TwoDShape.prototype.constructor=TwoDShape;
//augment prototype 扩展原型对象
TwoDShape.prototype.name='2D Shape';
</script>

JS是一种完全依靠对象的语言,所以没有类的概念,不能像Java那样直接继承构造器,而是通过new Shape()构造一个实体,通过实体属性完成相应的操作,继承实现后,我们对Shape()所进行的任何修改都不会影响TwoDShape(),Because我们继承的只是有构造器创建的实体

只继承于原型

function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function() {
    return this.name;
}

function TwoDShape(){}
TwoDShape.prototype=Shape.prototype;
TwoDShape.prototype.constructor=TwoDShape;
TwoDShape.prototype.name='2D Shape';

function Triangle(side,height){
    this.side=side;
    this,height=height;
}
Triangle.prototype=TwoDShape.prototype;
Triangle.prototype.constructor=Triangle;
Triangle.prototype.name='Triangle'
Triangle.prototype.getArea=function(){
    return this.side*this.height/2;
}

这种方法效率更高,仅通过原型就完成继承关系的构建,但是若子对象与父对象指向的是同一个对象,则子对象修改会影响父对象

var my=new Triangle(5,10)
my.toString()
"Triangle"
var s=new Shape() 
s.toString()
"Triangle"

创建临时构造器

function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function() {
    return this.name;
}

function TwoDShape(){}
// TwoDShape.prototype=Shape.prototype;
var F=function(){}
F.prototype=Shape.prototype;
TwoDShape.prototype=new F();
TwoDShape.prototype.constructor=TwoDShape;
TwoDShape.prototype.name='2D Shape';

function Triangle(side,height){
    this.side=side;
    this,height=height;
}
// Triangle.prototype=TwoDShape.prototype;
var E=function(){}
E.prototype=TwoDShape.prototype;
Triangle.prototype=new E();
Triangle.prototype.constructor=Triangle;
Triangle.prototype.name='Triangle'
Triangle.prototype.getArea=function(){
    return this.side*this.height/2;
}

这种写法子对象不会覆盖父对象

var my=new Triangle(5,10)
my.toString()
"Triangle"
var s=new Shape() 
s.toString()
"Shape"

简化代码,将继承部分封装成函数

function extend(Child,Parent){
    var F=function(){};
    F.prototype=Parent.prototype;
    Child.prototype=new F();
    Child.prototype.constructor=Child;
    Child.uber=Parent.prototype;//子对象访问父对象的方式
}

function Shape(){}
Shape.prototype.name='Shape';
Shape.prototype.toString=function(){
    var con=this.constructor;
    return con.uber?con.uber.toString()+','+this.name:this.name;
}

function TwoDShape(){}
extend(TwoDShape,Shape);
TwoDShape.prototype.name='2D Shape';

function Triangle(side,height){
    this.side=side;
    this.height=height;
}
extend(Triangle,TwoDShape);
Triangle.prototype.name='Triangle';
Triangle.prototype.getArea=function(){
    return this.side*this.height/2;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值