码迷,mamicode.com
首页 > 其他好文 > 详细

封装组合继承函数

时间:2015-10-31 18:33:45      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

通常的组合继承模式如下

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!