原型继承的实现

1 简化版本

function SuperClass(){...}

function SubClass(){...}

SubClass.prototype=new SuperClass();

SubClass.prototype.constructor=SubClass;

注意:该方法大多数情况下是正确的,但有时会出现问题。如当function SuperClass(name){this.name=name.toUpperCase();},在调用new SuperClass()时会出错。

 

2 比较通用的一个原型继承的实现

//该函数的child不继承parent的自定义属性
function
inherite(child,parent){ var F=function(){}; //F与parent共享一个原型 F.prototype=parent.prototype; //child的原型为F的实例 child.prototype=new F(); child.prototype.constructor=child; } function SuperClass(name){ this.name=name; } function SubClass(name,age){ SuperClass.call(this,name); this.age=age; } inherate(SubClass,SuperClass);

好处:避免创建一个父类(SuperClass)的实例,以及避免了一些父类构造函数的副作用

 

3  干净的原型继承

function SuperClass(){}

function SubClass(){}

SubClass.prototype=Object.create(SuperClass.prototype);

SubClass.prototype.constructor=SubClass;

 注意:Object.create()方法只有部分浏览器支持

posted on 2016-11-14 22:31  Jennica  阅读(234)  评论(0编辑  收藏  举报