2012-06-27 99 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中实现你的模块? –