时间:2021-07-01 10:21:17 帮助过:22人阅读
(1)组合继承(combination inheritance):
在子类构造函数中通过Super.call(this)来添加父类的属性,并通过让子类构造函数的prototype成为父类的实例来实现继承。缺点是会在子类构造函数中存储冗余的父类属性(因为他是父类的一个实例,而子类的实例又会覆盖一遍同样的属性),同时会调用两次父类的构造函数,并且也会导致继承链多了一层。
(function combineInherit(){
function SuperType(){
this.super="super";
}
SuperType.prototype.saySuper=function(){
}
function SubType(){
SuperType.call(this,arguments);
this.sub="sub";
}
SubType.prototype=new SuperType();
SubType.prototype.constructor=SubType;
SubType.prototype.saySub=function(){
}
var sub1=new SubType();
sub1.saySub();
})();继承链:

(2)寄生组合式继承(parasitic combination inheritance):
与组合继承不同在于,寄生组合式继承另子类构造函数的prototype不成为父类的实例,而是直接通过父类构造函数的prototype的引用来形成子类构造函数的prototype,最精简的方式就是另二者直接等同,这样不仅减少了一次父类构造函数的调用,减少了存在子类prototype中的冗余属性,同样也减少了一层继承链(并且这种情况下用instanceof判断仍然同属子类和父类)。
(function parasiticCombineInherit(){
function inheritPrototype(subType,superType){
subType.prototype=superType.prototype;
subType.prototype.constructor=subType;
}
function SuperType(){
this.super="super";
}
SuperType.prototype.saySuper=function(){
}
function SubType(){
SuperType.call(this,arguments);
this.sub="sub";
}
inheritPrototype(SubType,SuperType);
SubType.prototype.saySub=function(){
}
var sub=new SubType();
console.log(sub instanceof SuperType);
})();继承链:

(3)jQUery式经典继承
(function classicInherit(){
var initializing=false,
superPattern=/xyz/.test(function() {xyz;}) ? /\b_super\b/ : /.*/;
Object.subClass=function(properties){
var _super=this.prototype;
initializing=true;
var proto=new this();
initializing=false;
for(var name in properties){
proto[name]=typeof properties[name]=="function"&&
typeof _super[name]=="function"&&
superPattern.test(properties[name])?
(function(name,fn){
return function(){
var tmp=this._super;
this._super=_super[name];
var ret=fn.apply(this,arguments);
this._super=tmp;
return ret;
};
})(name,properties[name]):properties[name];
}
function Class(){
//init方法需要通过外部自定义传入
if(!initializing&&this.init){
this.init.apply(this,arguments);
}
}
Class.prototype=proto;
Class.constructor=Class;
Class.subClass=arguments.callee;
return Class;
}
})();以上就是详解JavaScript继承的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!