标签:
通常的组合继承模式如下
1 function Papa(){};
2 function Child(){
3 Papa.apply(this,arguments);
4 };
5 Child.prototype = new Papa();
6 Child.prototype.constructor = Child;
我们可以对这个模式进行封装
function classExtends(Class1,Class2){
Class2 = function(){
Class1.apply(this,arguments);
}
Class2.prototype = new Class1();
Class2.prototype.constructor = Class2;
return Class2;
}
以上的做法有些不足是 继承后的子类在实例化时添加第三个参数会比较困难;
所以我们可以尝试着做以下改良
1 function classExtends(Class1,Class2,bHaveOwnArgs){
2 Class2 = function(){
3 Class1.apply(this,arguments);
4 if(bHaveOwnArgs && arguments[2]){
5 for(var name in arguments[2]){
6 this[name] = arguments[2][name];
7 }
8 }
9 }
10 Class2.prototype = new Class1();
11 Class2.prototype.constructor = Class2;
12
13 return Class2;
14 }
看看以下的范例
function Person(name,age){
this.name = name;
this.age = age;
}
var Man = classExtends(Person,Man,true);
var vidy = new Man(‘vidy‘,30,{bWillBeARichMan:true});
Man.prototype.haveBigHouse = function(){
if(this.bWillBeARichMan) {
return ‘bigHouse to ‘+this.name;
}
}
console.log(vidy.haveBigHouse());//bighouse to vidy
标签:
原文地址:http://www.cnblogs.com/vidy/p/4925797.html