2015-06-09 52 views
0

考慮下面的代碼(jQuery的模式,我想):繼承的jQuery狀的圖案

 function child(){ 
      return new child.methods.init(); 
     } 

     child.methods = child.prototype = { 
      init: function(){ 
       return this; 
      }, 
      test: function(){ 
       console.log('test'); 
       return this; 
      } 
     } 

     //this code doesn't work 
     child.methods.prototype = { 
      test1: function(){ 
       console.log('test1'); 
       return this; 
      } 
     } 

     child.methods.init.prototype = child.methods; 

     //Using child chaining api. test() will work, but test1() will not. 
     child().test().test1(); 

我需要繼承其他子對象(文字對象給出了簡化)。 如何從對象繼承子函數模式?

+0

您正在尋找'child.methods.test1 = function(){...}'。哦,請不要使用jQuery模式,因爲它太混亂了。 – Bergi

回答

1

Child.method是iteself child.prototype。爲什麼你要在child.prototype/child.methods中創建一個新的原型屬性。你可以按照你的要求進行連接。

// Extend properties of existing methods/functions 
    function extendProperties (base, extension) { 
    for (var property in extension) { 
     try { 
     base[property] = extension[property]; 
     } catch (warning) { 
     } 
    } 
    } 
//Creating a new child 
    function createChild() { 
    return new child; 
    } 
//Create child function . Root function 
    function child() {console.log('child created')} 
//Prototype. Using .methods is not required. 
    child.methods = child.prototype = { 
    init: function() { 
     return this; 
    }, 
    test: function() { 
     console.log('test'); 
     return this; 
    } 
    } 
    //Extend existing functions methods. 
    //Here we are adding a new method in object of child and adding test1. 
    extendProperties(child.methods, { 
    test1: function() { 
     console.log('test1'); 
     return this; 
    } 
    }) 

//Achieving chaining. 
createChild().test().test1() 
+0

child.methods.prototype不工作,因爲它不是構造函數(我的意思是你不能通過使用'new child.methods'來獲取新對象)。 – Helvdan

+0

我可以通過拒絕酷對象文字符號並使用'this'屬性內部的方法函數來實現類似的結果,例如:'var methods = function(this.test = function(){...})'並且擴展' methods.prototype'與選擇的對象。 – Helvdan

+0

@helven是的,我們可以使用對象字面符號來實現同樣的效果,並感謝您糾正我。謝謝 –