2012-06-27 97 views
5

我想繞過javascript模塊,但我不確定如何將模塊拆分成更多的子模塊。我已經讀過,由於性能的原因,嵌套函數並不是一個好主意,那麼如何分解模塊中的函數呢?例如,假設我有以下模塊:Javascript模塊模式,嵌套函數和子模塊

var Editor = {}; 

Editor.build = (function() { 
    var x = 100; 
    return { 
     bigFunction: function() { 
      // This is where I need to define a couple smaller functions 
      // should I create a new module for bigFunction? If so, should it be nested in Editor.build somehow? 
     } 
    }; 
})(); 

bigFunction只與Editor.build有關。我應該將構成bigFunction的較小函數附加到原型bigFunction對象嗎?我甚至不確定這是否合理。

var Editor = {}; 

Editor.build = (function() { 
    var x = 100; 
    return { 
     bigFunction: function() { 
      bigFunction.smallFunction(); 
      bigFunction.prototype.smallFunction = function(){ /*do something */ }; 
      // not sure if this even makes sense 
     } 
    }; 
})(); 

有人可以把我扔在正確的方向嗎?網上有太多誤導性的信息,並且只是像如何處理這種模塊化的明確指南。

謝謝。

回答

0

這裏有一個片段我用做名字輸入:

var dynamicCounter = 0; 
    //custom dropdown names 
    var createContainerNames = function() { 
     function Names() { 
      this.id = "Tasks_" + dynamicCounter + "__ContainerId"; 
      this.name = "Tasks[" + dynamicCounter + "].ContainerId"; 
      this.parent = "task" + dynamicCounter + "Container"; 
     } 
     Names.prototype = { constructor: Names }; 
     return function() { return new Names(); }; 
    }(); 

然後我使用它:

var createdNames = createContainerNames(); 
    var createdId = createdNames.id; 
    dynamicCounter++; 
    var differentNames = createContainerNames(); 
    var differentId = differentNames.id; 

另一種方法是做到這一點:

var NameModule = function(){ 

//"private" namemodule variables 
var priv1 = "Hello"; 

//"private namemodule methods 
function privMethod1(){ 
    //TODO: implement 
} 

//"public namemodule variables 
var pub1 = "Welcome"; 

//"public" namemodule methods 
function PubMethod(){ 
    //TODO: pub 
} 

return { 
    pub1 : pub1, 
    PubMethod: PubMethod 
}; 

然後使用它

var myPubMethod = new NameModule(); 
myPubMethod.PubMethod(); 
var pubVar = myPubMethod.pub1; 

編輯

你也可以採取這種做法:

var mod = function(){ 
this.modArray = []; 
}; 

mod.prototype = { 

//private variables 
modId: null, 

//public method 
AddToArray: function (obj) { 
    this.modArray.push(obj); 
} 
} 
+0

它似乎並不特別適用於持有的構造及其在封閉的原型,這意味着你不能輕易稍後擴展或修改原型。很難看到標準函數聲明和原型分配的好處。模塊模式實際上是關於模塊的,即一個對象,而不是構造器。 – RobG

+0

@RobG - 第一個肯定更多是獨立的。這和標準函數的區別在於你獲得獨特的對象。第二種方法更貼近模塊模式。我可以把第三個使用原型作爲擴展方法。 –

+0

@RobG - 你如何在JavaScript中實現你的模塊? –