本文系统介绍 JavaScript 中的六种继承模式,包括原型链、构造函数、组合继承、原型式、寄生式及寄生组合式继承。重点解析各模式的实现原理、优缺点及适用场景,特别是寄生组合式继承如何优化性能并解决重复调用构造函数的问题,帮助开发者选择最佳继承方案。
原型链继承及其局限
原型链继承的核心在于理解构造函数、原型对象与实例之间的关联。每个构造函数都拥有一个原型对象,该原型对象包含一个指向构造函数的指针;同时,实例对象内部包含一个指向原型对象的指针。验证原型与实例关系时,通常使用 instanceof 操作符。
原型链继承存在明显局限:若使用字面量方式重写原型,会切断原有的继承关系;此外,由于引用类型属性存储在原型中,所有实例会共享这些属性,导致数据冲突;同时,子类型在初始化时无法向超类型构造函数传递参数。
function Parent(){
this.name='mike';
}
function Child(){
this.age=12;
}
//儿子继承父亲(原型链)
Child.prototype=new Parent();//Child继承Parent,通过原型形成链条
var test=new Child();
console.log(test.age);
console.log(test.name);//得到被继承的属性
//孙子继续原型链继承儿子
function Brother(){
this.weight=60;
}
Brother.prototype=new Child();//继承原型链继承
var brother=new Brother();
console.log(brother.name);//继承了Parent和Child,弹出mike
console.log(brother.age);//12
console.log(brother instanceof Child);//ture
console.log(brother instanceof Parent);//ture
console.log(brother instanceof Object);//ture
构造函数与组合继承分析
构造函数继承(亦称伪造对象或经典继承)通过调用超类型构造函数来实现属性继承。这种方式解决了原型链继承中引用共享和参数传递的问题,但由于方法定义在构造函数内部,导致函数无法复用,因此通常需要结合原型链使用。
function Parent(age){
this.name=['mike','jack','smith'];
this.age=age;
}
function Child(age){
Parent.call(this,age);//把this指向Parent,同时还可以传递参数
}
var test=new Child(21);
console.log(test.age);//21
console.log(test.name);
test.name.push('bill');
console.log(test.name);//mike,jack,smith,bill
组合继承结合了原型链和构造函数继承的优点:利用原型链继承原型上的属性和方法以实现函数复用,同时通过借用构造函数继承实例属性以确保每个实例拥有独立属性。然而,该模式存在性能缺陷:无论何种情况,超类型构造函数都会被调用两次——一次在创建子类型原型时,另一次在子类型构造函数内部。
function Parent(age){
this.name=['mike','jack','smith'];
this.age=age;
}
Parent.prototype.run=function(){
return this.name+' are both '+this.age;
}
function Child(age){
Parent.call(this,age);//给超类型传参,第二次调用
}
Child.prototype=new Parent();//原型链继承,第一次调用
var test1=new Child(21);//写new Parent(21)也行
console.log(test1.run());//mike,jack,smith are both 21
var test2=new Child(22);
console.log(test2.age);
console.log(test1.age);
console.log(test2.run());
//这样可以使test1和test2分别拥有自己的属性age同时又可以有run方法
原型式与寄生式继承
原型式继承允许基于现有对象创建新对象,无需定义自定义类型。其核心要求是必须存在一个可作为新对象基础的原型对象,通过复制该原型来实现对象创建。
function object(o){
function F(){};
F.prototype=o;
return new F();
}
var person={
name:'nicho',
friends:['shell','jim','lucy']
}
var anotherPerson = object(person);
anotherPerson.name = 'Greg';
anotherPerson.friends.push('Rob');
console.log(anotherPerson.friends);//["shell", "jim", "lucy", "Rob"]
var yetAnotherPerson = object(person);
yetAnotherPerson.name = 'Linda';
yetAnotherPerson.friends.push('Barbie');
console.log(yetAnotherPerson.friends);//["shell", "jim", "lucy", "Rob", "Barbie"]
console.log(person.friends);//["shell", "jim", "lucy", "Rob", "Barbie"]
ECMAScript 5 规范引入了 Object.create() 方法,使原型式继承标准化。该方法接收两个参数:第一个参数是用作新对象原型的对象,第二个参数(可选)是用于为新对象定义额外属性的对象描述符。
var person2={
name:'nicho',
friends:['shell','jim','lucy']
};
var anoP2=Object.create(person2);
anoP2.name="Greg";
anoP2.friends.push('Rob');
console.log(anoP2.friends);//["shell", "jim", "lucy", "Rob"]
var yetP2=Object.create(person2);
yetP2.name="Linda";
yetP2.friends.push('Barbie');
console.log(yetP2.friends);//["shell", "jim", "lucy", "Rob", "Barbie"]
console.log(person2.friends);//["shell", "jim", "lucy", "Rob", "Barbie"]
/*以这种方式指定的任何属性都会覆盖原型对象上的同名属性。*/
var threeP=Object.create(person,{
name:{value:'red'}
});
console.log(threeP.name);//red,如果threeP中无name则输出person2里的name值nicho
寄生式继承的思路类似于寄生构造函数和工厂模式。它创建一个仅用于封装继承过程的函数,在函数内部对对象进行增强处理,最后返回该对象。这种方式看似完成了所有工作,实则是在原有对象基础上进行扩展。
function object(o){
function F(){};
F.prototype=o;
return new F();
};
function createAnother(o){
var cl=object(o);
cl.sayHi=function(){
console.log('hi');
}
return cl;
};
var person={
name:'nick',
friends:['shelby','court','van']
}
var anotherPerson=createAnother(person);
anotherPerson.sayHi();//hi
console.log(anotherPerson.name);//nick
console.log(anotherPerson.friends);//["shelby", "court", "van"]
/*这个例子中的代码基于 person 返回了一个新对象—— anotherPerson 。 新对象不仅具有 person
的所有属性和方法,而且还有自己的 sayHi() 方法*/
寄生组合式继承优化方案
由于组合继承会调用两次超类型构造函数,导致子类型原型最终包含超类型对象的全部实例属性,从而需要在调用子类型构造函数时重写这些属性。为了解决这一问题,寄生组合式继承应运而生。
寄生组合式继承的基本思路是:借用构造函数来继承属性,通过原型链的混成形式来继承方法。关键优化在于不必为了指定子类型原型而调用超类型构造函数。其本质是利用寄生式继承来继承超类型的原型,再将结果指定给子类型的原型。
function SuperType(name){
this.name=name;
this.colors=['red','blue','green'];
}
SuperType.prototype.sayName=function(){
console.log(this.name);
}
function SubType(name,age){
SuperType.call(this,name);
this.age=age;
}
function object(o){
function F(){};
F.prototype=o;
return new F();
};
/*inheritPrototype此函数第一步是创建超类型原型的一个副本。第二步是为创建的副本添加constructor属性,
* 从而弥补因重写原型而失去的默认的constructor属性,第三步将新创建的对象(副本)赋值给子类型的原型*/
function inheritPrototype(subType,superType){
var prototype=object(superType.prototype);//创建对象
prototype.constructor=subType;//增强对象
subType.prototype=prototype;//指定对象
}
inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge=function(){
console.log(this.age);
}
var p=new SubType('xiaoli',24);
console.log(p.sayName());
console.log(p.sayAge());
console.log(p.colors)
该方法的主要优势在于仅调用一次父类构造函数,避免了在子类型原型上创建不必要的多余属性。同时,原型链保持不变,使得 instanceof 和 isPrototypeOf() 方法仍能正常使用,兼顾了性能与兼容性。
以上内容涵盖了 JavaScript 中几种主要继承方法的介绍,旨在为开发者提供清晰的参考与指导。