封裝組合繼承函數

一般的組合繼承模式以下app

1 function Papa(){}; 2 function Child(){ 3     Papa.apply(this,arguments); 4 }; 5 Child.prototype = new Papa(); 6 Child.prototype.constructor = Child;

咱們能夠對這個模式進行封裝    this

 function classExtends(Class1,Class2){ Class2 = function(){ Class1.apply(this,arguments); } Class2.prototype = new Class1(); Class2.prototype.constructor = Class2; return Class2; }

以上的作法有些不足是  繼承後的子類在實例化時添加第三個參數會比較困難;spa

因此咱們能夠嘗試着作如下改良prototype

 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 }

看看如下的範例code

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
相關文章
相關標籤/搜索