以下是几种js中完成继续的方式要领,它们也是各自有各自的优瑕玷,挑选哪种依据本身的运用而定,最适合本身的才是最好的.
经由过程原型链继续
function SuperType(){
this.name = 'yahualingfeng';
}
SuperType.prototype.friends = ['David','Bob','Lucy'];
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(){
this.age = 30;
}
SubType.protoType = new SuperType();//经由过程原型对象继续SuperType
var subType1 = new SubType();
var subType2 = new SubType();
subType1.friends.push('Jake');
console.log(subType1.friends); // ['David','Bob','Lucy','Jake']
console.log(subType2.friends); // ['David','Bob','Lucy','Jake']
瑕玷:
- 援用范例的值在原型中会被一切实例同享.
- 不能向超类的组织函数中通报参数
借用组织函数继续
借用组织函数继续是将超类(SuperType
)一切的属性和要领都写在组织函数中,末了在函数(SubType
)体内经由过程call
要领挪用超类.
function SuperType(){
this.name = 'yuhualingfeng';
this.friends =['David','Bob','Lucy'];
this.sayName = function(){
alert(this.name);
}
}
function SubType(){
SuperType.call(this);
}
var subType = new SubType();
subType.sayName();
瑕玷:要领的定义都存在组织函数中,致使函数没法被复用.
组合继续
组合继续是原型链继续和组织函数继续的连系体,连系了两者的长处,即完成了函数的复用,也不会致使援用范例值在多个实例中同享.
function SuperType(){
this.name='yuhualingfeng';
this.friends=['David','Bob','Lucy'];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(){
SuperType.call(this);
}
SubType.prototype = new SuperType();
var subType = new SubType();
瑕玷:
- 超类函数被实行了两次.
- 超类组织函数
SuperType
本身的属性(name
,friends
)被反复定义,即出现在SubType
的组织函数中,也出现在SubType
的原型对象中.
原型继续
原型继续是继续自一个对象而不是援用范例.
function object(obj){
function F(){}
F.prototype = obj;
return new F();
}
这里的object要领吸收obj对象,并将对象赋值给一个空函数的原型,并返回空函数的实例.
var person = {
name:'yuhualingfeng',
friends:['David','Bob','Lucy']
};
var anotherPerson = object(person);
anotherPerson.name = 'Jake';
anotherPerson.friends.push('Marry');
console.log(anotherPerson.friends); //['David','Bob','Lucy','Marry']
console.log(person.friends); //['David','Bob','Lucy','Marry']
如果不想建立组织函数,只想让一个对象和另一个对象保持一致的情况下,原型继续是完全可以胜任的,不过有一点要注意的是,如果继续的属性值为援用范例时,照样会相互影响的.
寄生继续
寄生继续是基于原型继续的基础上扩大本身的属性和要领.
function createrAnother(obj){
var clone = object(obj);
clone.sayHi=function(){
alert('Hi!');
}
return clone;
}
var person = {
name:'yuhualingfeng'
};
var anotherPerson = createAnother(person);
anohterPerson.sayHi(); // Hi
寄生继续也是和原型继续一样也是继续对象,并产出对象.
寄生组合继续
望文生义,寄生组合继续是集寄生继续和组合继续的连系体,它连系了两者的长处.
//继续Supertype的原型对象
function inheritProtoType(SuperType,SubType){
var prototype = object(SuperType.prototype);
prototype.constructor = SubType;
SubType.prototype = prototype;
}
function SuperType(){
this.name = 'yuhualingfeng';
this.friends = ['David','Bob','Lucy'];
}
function SubType(){
////继续Supertype的组织函数属性
SuperType.call(this);
this.age = 30;
}
inheritProtoType(SuperType,SubType);
var subType = new SubType();
寄生组合继续是前面几种继续头脑碰撞在一起的产品,是实行效力最高也是运用面最广的.
总结
原型链继续
是经由过程为原型对象赋值,不足之处为援用范例值会被多个实例同享,组织函数继续
处理了原型链继续
的题目,同时也暴露出新的题目是函数的复用没法完成,然后我们连系两者的优瑕玷,组织出了组合继续
,组合继续
基本上满足了我们想要的继续效果.
考虑到实行的效力,我们构想出了寄生继续
(基于原型继续),并将寄生继续
和组合继续
连系,终究得出了继续的最优处理方案’寄生组合继续
.