网上讨论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'
}