
原型链的这个特性,和继承很相似,所以自然而然,我们可以利用它来实现继承机制。而原型链对instanceof的支持,使得它成为很好的选择。
我们定义extend函数,这个函数接受两个参数,第一个是父类,第二个是子类,如下所示:
function extend(ParentClass, ChildClass) {...return ChildClass;}这个函数对子类进行处理,并返回子类。处理的逻辑如下:var pp = ParentClass.prototype,cp = ChildClass.prototype;function T() {};T.prototype = pp;ChildClass.prototype = new T();为了连接原型链,需要创建一个父类的实例,并将其赋给子类的原型属性。但我们不希望在extend方法里面就实例化父类,所以引入了一个中间类T,以解决这个问题。ChildClass.prototype[name] = (function(pm, cm) {return function() {var _super = this.super;this.super = pm;var result = cm.apply(this, arguments);this.super = _super;return result;};})(pp[name], cp[name]);属性ChildClass.prototype[name] = cp[name];构造器
ChildClass.super = ParentClass;如何使用

实现这个设计的代码如下:
function People(firstname, lastname) {this.firstname = firstname;this.lastname = lastname;}function Employee(firstname, lastname, company) {Employee.super.apply(this, arguments);this.company = company;}function Manager(firstname, lastname, company, title) {Manager.super.apply(this, arguments);this.title = title;}我们希望对每个人都有一个描述,People是姓+名;员工在姓+名之后,还包括公司名称;而经理在员工的描述之后,还包括职位。代码如下:People.prototype.summary = function() {return this.firstname + " " + this.lastname;};Employee.prototype.summary = function() {return this.super.call(this) + ", " + this.company;};Manager.prototype.summary = function() {return this.super.call(this) + ", " + this.title;};在所有的成员方法都已经定义好之后,声明类的继承(必须先定义方法,再声明类的继承,否则无法在方法中使用this.super调用父类方法!):extend(People, Employee);extend(Employee, Manager);使用这些类就比较简单,直接new就好了:
var people = new People("Alice", "Dickens");var employee = new Employee("Bob", "Ray", "Alibaba");var manager = new Manager("Calvin", "Klein", "Alibaba", "Senior Manager");console.log( people.summary() ); //Alice Dickensconsole.log( employee.summary() ); //Bob Ray, Alibabaconsole.log( manager.summary() ); //Calvin Klein, Alibaba, Senior Manager这篇文章不错吧,那就给个赞吧!