Javascript模块模式、嵌套函数和子模块
我试图将注意力集中在javascript模块上,但我不确定如何将一个模块拆分为更多的子模块。我已经读到,由于性能原因,嵌套函数并不是一个好主意,那么如何在模块中分解函数呢?例如,假设我有以下模块:Javascript模块模式、嵌套函数和子模块,javascript,module,Javascript,Module,我试图将注意力集中在javascript模块上,但我不确定如何将一个模块拆分为更多的子模块。我已经读到,由于性能原因,嵌套函数并不是一个好主意,那么如何在模块中分解函数呢?例如,假设我有以下模块: var Editor = {}; Editor.build = (function () { var x = 100; return { bigFunction: function () { // This is where I need to
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
}
};
})();
有人能把我往正确的方向扔吗?网上有太多误导性的信息,我想知道如何处理这种模块化
谢谢。以下是我用来为输入命名的代码片段:
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);
}
}
将构造函数及其原型保存在闭包中似乎不是特别有用,这意味着您以后无法轻松地扩展或修改原型。很难看出标准函数声明和原型分配有什么好处。模块模式实际上是关于模块的,即一个对象,而不是构造函数。@RobG-第一个模式更像是一个独立的模式。这与标准函数的区别在于,您将获得唯一的对象。第二种方法更符合模块模式。我可以使用第三种模式,其中使用prototype作为扩展方法。@RobG-如何在javascript中实现模块?我只在需要在闭包中保留“私有”变量和函数的情况下使用模块模式(例如,专门用于它所包含的模块的帮助器方法)。如果没有,我不会使用模块模式,尽管我可能会使用IIFE来有条件地创建函数(例如,使用特性检测),其中闭包是工件而不是特性。马匹在球场上奔跑。