Javascript类继承

网上讨论Javascript类继承的文章比较多,比如阮一峰博客上的Javascript 面向对象编程系列文章。
这里只针对使用prototype方式作下介绍,inherit是自己实现的一个函数,用于辅助设置子类prototype.

Javascript继承

示例如下:

function inherit(type, object)
{
    var sp = type.prototype;
    for(var i in sp)
    {
        if(!(i in object))
            object[i] = sp[i];
    }

    var args = [].slice.call(arguments,2);
    type.apply(object, args);
}

function Animal(color)
{
    this.color = color;
}

Animal.prototype.type = function()
{
    return 'animal';
};

Animal.prototype.hello = function()
{
    var s = 'It is ' + this.color + ' ' + this.type() + '.';
    document.body.innerText += s;
};

function Dog()
{
    inherit(Animal, this, 'yellow');
}

Dog.prototype.type = function()
{
    return 'dog';
};

window.onload = function()
{
    var dog = new Dog();
    dog.hello();
}

运行会输出: It is yellow dog. 

 

调用基类方法

在上面示例后面加入下面代码:

Dog.prototype.hello = function()
{
    document.body.innerText += 'Hello, ';
    Animal.prototype.hello.call(this);
};

运行会输出: Hello, It is yello dog.

由于存在多重继承的情况,所以Javascript类继承时并不推荐在子类型实例中存储父类型来简化调用基类方法.

 

多重继承

假定有两个基类Animal和Pet, Dog子类从两个基类同时继承,则可以调用两次inherit来实现。

function Dog()
{
    inherit(Animal, this);
    inherit(Pet, this);

    //self init
    this.name = 'dog'
}

 

 

转载于:https://www.cnblogs.com/ralfy/archive/2013/04/12/3012259.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值