配色: 字号:
TDD测试驱动的javascript开发------ javascript的继承
2016-11-01 | 阅:  转:  |  分享 
  
TDD测试驱动的javascript开发------javascript的继承



说起面向对象,人们就会想到继承,常见的继承分为2种:接口继承和实现继承。接口继承只继承方法签名,实现继承则继承实际的方法。



由于函数没有签名,在ECMAScript中无法实现接口继承,只支持实现继承。



1.原型链



1.1原型链将作为实现继承的主要方法,基本思想是利用原型让一个引用类型继承另一个引用类型的属性和方法。



构造函数---原型---实例之间的关系:



每一个构造函数都有一个原型对象,原型对象包含一个指向构造函数的指针,而实例都包含一个指向原型对象的内部指针。



functionSuperType(){

this.property=true;

}



SuperType.prototype.getSuperValue=function(){

returnthis.property;

};



functionSubType(){

this.subproperty=false;

}



SubType.prototype=newSuperType();//通过原型链实现继承



SubType.prototype.getSubValue=function(){

returnthis.subproperty;

};



varsubInstance=newSubType();



varsuperInstance=newSuperType();



TestCase("testextends",{



"testsuperInstancepropertyshouldbetrue":function(){

assertEquals(true,superInstance.property);

},

"testsuperInstancegetSuperValue()shouldbereturntrue":function(){

assertEquals(true,superInstance.getSuperValue());

},

"testsubInstancepropertyshouldbefalse":function(){

assertEquals(false,subInstance.subproperty);

},

"testsubInstancecouldvisitsupermethod":function(){

assertEquals(true,subInstance.getSuperValue());//SubType继承SuperType,并调用父类的方法

}

});



注:要区分开父类和子类的属性名称,否则子类的属性将会覆盖父类的同名属性值:看如下代码:





functionSubType(){

this.property=false;

}

SubType.prototype.getSubValue=function(){

returnthis.property;

};

functionSuperType(){

this.property=true;

}



SuperType.prototype.getSuperValue=function(){

returnthis.property;

};



SubType.prototype=newSuperType();//通过原型链实现继承





varsubInstance=newSubType();



varsuperInstance=newSuperType();



TestCase("testextends",{



"testsuperInstancepropertyshouldbetrue":function(){

assertEquals(true,superInstance.property);//父类的property值为true

},

"testsuperInstancegetSuperValue()shouldbereturntrue":function(){

assertEquals(true,superInstance.getSuperValue());//superInstance调用方法

},

"testsubInstancepropertyshouldbefalse":function(){

assertEquals(false,subInstance.property);//子类的property属值为false

},

"testsubInstancecouldvisitsupermethod":function(){

assertEquals(false,subInstance.getSuperValue());//SubType继承SuperType,并调用父类的方法,可以属性被覆盖了,返回false

}

});

续:当然,如果我们不要求对属性值进行初始化的时候,就不必考虑这个问题,我们会采用上一章讲的构造函数模式+原型模式来创建类和实现继承关系。

当以读取模式访问一个实例属性时,首先会在实例中搜索该属性,如果没有找到该属性,则继续在实例的原型中寻找。在通过原型链实现继承的情况下,会继续沿着原型链继续向上





subExtends.getSuperValue()

首先在实例中查找,然后在SubType.prototype,最后在SuperType.prototype中找到。

补充:所有函数的默认原型都是Object的实例,因此默认原型都会包含一个内部指针,指向Object.prototype,这也正是所有自定义类型都会继承toString()、valueOf()等默认方法的原因。



1.2确定原型和实例的关系



方法一:使用instanceof操作符----只要该实例是原型链中出现过的构造函数,结果就会返回true





functionSuperType(){

this.property=true;

}



SuperType.prototype.getSuperValue=function(){

returnthis.property;

};



functionSubType(){

this.subproperty=false;

}



SubType.prototype=newSuperType();//通过原型链实现继承



SubType.prototype.getSubValue=function(){

returnthis.subproperty;

};



varsubInstance=newSubType();



TestCase("testextends",{



"testsubInstanceshouldinstanceofObject":function(){

assertInstanceOf(Object,subInstance);

},

"testsubInstanceshouldinstanceofSuperType":function(){

assertInstanceOf(SuperType,subInstance);

},

"testsubInstanceshouldinstanceofSubType":function(){

assertInstanceOf(SubType,subInstance);

}

});



方法二:使用isPrototypeOf()方法----只要原型链中出现过该原型,都可以说是该原型链所派生的实例的原型,结果会返回true





functionSuperType(){

this.property=true;

}



SuperType.prototype.getSuperValue=function(){

returnthis.property;

};



functionSubType(){

this.subproperty=false;

}



SubType.prototype=newSuperType();//通过原型链实现继承



SubType.prototype.getSubValue=function(){

returnthis.subproperty;

};



varsubInstance=newSubType();



TestCase("testextends",{



"testsubInstanceisPrototypeOfObject":function(){

assertEquals(true,Object.prototype.isPrototypeOf(subInstance));

},

"testsubInstanceisPrototypeOfSuperType":function(){

assertEquals(true,SuperType.prototype.isPrototypeOf(subInstance));

},

"testsubInstanceisPrototypeOfSubType":function(){

assertEquals(true,SubType.prototype.isPrototypeOf(subInstance));

}

});



注:在实践中,我们很少会单独的使用原型链,因为它存在两个问题:

一、引用类型值的原型:包含引用类型值的原型属性会被所有实例共享,这也正是为什么要在构造函数中定义属性,而不在原型中定义属性的原因



二、创建子类型的实例时,不能向超类型的构造函数中传递参数。



1.3借用构造函数(伪造对象----经典继承)



原理:在子类型构造函数的内部调用超类型的构造函数



functionSuperType(name){

this.name=name;

this.friends=[''tong'',''feng''];

}



functionSubType(name,age){

SuperType.call(this,name);

}



varsubInstance=newSubType("tongtong",26);



subInstance.friends.push(''ty'');



varsubInstance2=newSubType("fengfeng",27);



TestCase("testconstructorextends",{

"testsubInstancefriendsproperty":function(){

assertEquals("ty",subInstance.friends[2]);//将typush到数组

},

"testsubInstance2friendslength":function(){

assertEquals(2,subInstance2.friends.length);//subInstance2friends属性没有改变

}

});



1.4组合继承(经典伪继承)-----推荐模式

将原型链和借用构造函数的技术组合到一块,使用原型链实现对原型属性和方法的继承,通过借用构造函数来实现对实例属性的继承





functionSuperType(name){

this.name=name;

this.friends=[''tong'',''feng''];

}

SuperType.prototype.sayName=function(){

returnthis.name;

};



functionSubType(name,age){

//继承属性

SuperType.call(this,name);//调用构造函数

this.age=age;

}

//继承方法

SubType.prototype=newSuperType();//调用构造函数



SubType.prototype.sayAge=function(){

returnthis.age;

};



varsubInstance=newSubType("tongtong",26);



subInstance.friends.push(''ty'');



varsubInstance2=newSubType("fengfeng",27);



TestCase("testextends",{



"testsubInstancenameproperty":function(){

assertEquals("tongtong",subInstance.sayName());

},

"testsubInstance2nameproperty":function(){

assertEquals("fengfeng",subInstance2.sayName());

},

"testsubInstancefriendsproperty":function(){

assertEquals("ty",subInstance.friends[2]);//将typush到数组

},

"testsubInstance2friendslength":function(){

assertEquals(2,subInstance2.friends.length);//subInstance2friends属性没有改变

}

});

这种继承的缺点:将会2次调用构造函数,性能一般,解决办法:参见1.7寄生组合式继承

1.5原型式继承



这种方法没有严格意义上的构造函数,思想是借助原型可以基于已有的对象创建新的对象,同时还不必因此创建自定义类型。



它要求你必须有一个对象可以作为另一个对象的基础。如果有这么一个对象,可以把它传递给object()函数,然后该函数就会返回一个新对象。

functionobject(o){

functionF(){

}



F.prototype=o;

returnnewF();

}



varperson={

name:"tongtong",

friends:["feng","tong"]

};



varanother=object(person);

another.name="newtong";

another.friends.push(''lan'');



varother=object(person);



TestCase("testprototypeextends",{



"testanotherisextendspersonnameproperty":function(){

assertEquals("newtong",another.name);

},

"testpersonfirendspropertylengthis3":function(){

assertEquals(3,person.friends.length);

},

"testotherfirendspropertylengthis3":function(){

assertEquals(3,other.friends.length);

}

});



person作为另一个对象的基础,我们把它传入到object()中,然后该函数就会返回一个新对象,这个对象将person做为原型。

ECMAScript通过Object.create()方法规范了原型式继承,在传入一个参数的时候,Object.create()与object()方法的行为相同。



varperson={

name:"tongtong",

friends:["feng","tong"]

};

varanother=Object.create(person);

another.name="lisa";

another.friends.push("lan");

TestCase("testprototypeextends",{



"testanotherisextendspersonnameproperty":function(){

assertEquals("lisa",another.name);

},

"testpersonfirendspropertylengthis3":function(){

assertEquals(3,person.friends.length);

}

});

如果传入2个参数,第二个参数会覆盖同名参数

varperson={

name:"tongtong",

friends:["feng","tong"]

};

varanother=Object.create(person,{

name:{

value:"claire"

}

});



another.friends.push(''lalala'');

TestCase("testprototypeextends",{



"testanotherisextendspersonnameproperty":function(){

assertEquals("claire",another.name);

},

"testpersonfirendspropertylengthis3":function(){

assertEquals(3,person.friends.length);

}

});



在只想让一个对象与另一个对象保持类似的情况下,又没必要创建构造函数的时候,原型式继承OK.(它和原型模式一样哦,引用类型的值都会被共享)。

1.6寄生式继承



思路:与寄生构造和工厂模式类似,创建一个仅用于封装继承过程的函数,该函数在内部以某种方式来增强对象,最后再像它真的做了所以工作一样返回。



//这是一个函数哦

functioncreateAnother(original){

// varclone=object(original);//创建一个新对象

varclone=Object.create(original);

clone.sayThis=function(){//增强对象

returnoriginal;

};

returnclone;//返回对象

};



varperson={

name:"tong",

friends:[''tong'',''feng'']

};



varanother=createAnother(person);



TestCase("testprototypeextends",{

"testanotherisextendspersonnameproperty":function(){

assertEquals("tong",another.sayThis().name);

}

});

;

缺点:使用寄生式继承来为对象添加函数,会因为函数不能复用而降低效率(和构造函数模式相似)

1.7寄生组合式继承------最佳方案

所谓寄生组合式继承,即通过借用构造函数来继承属性,通过原型链的混合形式来继承方法,



思路:不必为了指定子类型的原型而调用超类型的构造函数,我们所需的无非就是超类型原型的一个副本而已。



本质上:使用寄生式继承来继承超类型的原型,然后再将结果指定给子类型的原型



特点:寄生式继承是引用类型最理想的继承方式



functionSuperType(name){

this.name=name;

this.colors=[''red'',''green''];

}



SuperType.prototype.sayName=function(){

returnthis.name;

};

/

1.创建父类型的一个副本

2.弥补创建副本时所丢失的constructor属性

3.将新的副本赋值给子类型的原型

@paramsubType

@paramsuperType

/

functioninheritPrototype(subType,superType){

varobject=Object.create(superType.prototype);//创建对象

object.constructor=subType;//增强对象

subType.prototype=object; //指定对象

}



functionSubType(name,age){

SuperType.call(this,name);//调用构造函数

this.age=age;

}



inheritPrototype(SubType,SuperType);



SubType.prototype.sayAge=function(){

returnthis.age;

};







varsubInstance1=newSubType(''feng'',28);

subInstance1.colors.push(''yellow'');



varsubInstance2=newSubType(''tong'',25);



TestCase("testparasiticextends",{

"testsubInstance1namepropertyshouldbefeng":function(){

assertEquals("feng",subInstance1.name);

},

"testsubInstance2namepropertyshouldbetong":function(){

assertEquals(''tong'',subInstance2.name);

},

"testsubInstance1colorspropertylengthshouldbe3":function(){

assertEquals(3,subInstance1.colors.length);

},

"testsubInstance2colorspropertylengthshouldbe2":function(){

assertEquals(2,subInstance2.colors.length);

},

"testsubInstance1sayAgemethodshouldbereturn28":function(){

assertEquals(28,subInstance1.sayAge());

},

"testsubInstance2sayAgemethodshouldbereturn25":function(){

assertEquals(25,subInstance2.sayAge());

},

"testsubInstance1shouldbeinstanceofSuperType":function(){

assertInstanceOf(SuperType,subInstance1);

}



});





1.8总结



1.8.1ECMAScript支持面向对象编程,但不使用类或者接口,对象可以在代码执行过程中创建和增强。



1.8.2创建对象的几种方式:



构造函数模式:可以创建自定义的引用类型,使用new操作符



缺点:在每个实例上都要重新创建,无法复用,包括函数



优点:与对象的松耦合



适用场合:当属性或者方法不做共享属性或者方法的时候(比如引用类型的属性),不建议单独使用。

原型模式:使用构造函数的prototype属性来指定那些共享的属性和方法



优点:所有成员都可以共享属性和方法



缺点:没有私有属性值

适用场合:所以的属性和方法都可以被共享的时候,不建议单独使用

组合使用构造函数和原型模式:使用构造函数定义实例属性,使用原型定义共享属性和方法。



优点:解决了原型模式共享引用类型的属性的问题,也解决了构造函数不能共享属性的问题。



缺点:实现继承的时候,将会2次调用父类型的构造函数。性能问题。

使用场合:使用最广泛的定义引用类型的一种默认模式。



动态原型模式:保持了构造函数和原型的优点,把所有的信息封装在构造函数内,在有必要的情况下进行初始化原型。

稳妥构造函数模式:适合在安全环境中使用。

1.8.3javascript的继承:

javascript主要通过原型链事实现继承。



原型链的继承:原型链的构建是通过将一个类型的实例赋值给另一个构造函数的原型实现的。



缺点:对象实例共享所有继承的属性和方法,因此不宜单独使用。



借用构造函数继承:在子类构造函数的内部调用超类型的构造函数。call()apply()

缺点:没有函数的复用,不建议单独使用

组合继承:使用原型链继承共享的属性和方法,而通过借用构造函数继承实例属性。

缺点:将会调用两次构造函数,会有性能问题



原型式继承:可以在不必预定义构造函数的情况下实现继承,其本质是执行对给定对象的浅复制,而复制的副本还可以得到进一步的改造。



优点:在没有必要创建构造函数,只是让一个对象与另一个对象保持类似的情况下,原型式继承OK.

缺点:共享属性和方法

寄生式继承:与原型式继承非常相似,基于对象获某些信息创建一个对象,然后增强对象,最后返回对象



优点:解决组合继承多次调用父类的构造函数而导致低效率问题。(可以与组合模式一起使用)



缺点:使用寄生式继承来为对象添加函数,会由于不能做到函数复用而降低效率,与构造函数模式类似。

寄生组合式继承:集寄生式继承和组合继承的优点于一身,是实现基于类型继承的最有效方式。

献花(0)
+1
(本文系thedust79首藏)