gpt4 book ai didi

Javascript 模块模式、嵌套函数和子模块

转载 作者:搜寻专家 更新时间:2023-11-01 04:38:23 26 4
gpt4 key购买 nike

我正在努力研究 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 的较小函数附加到原型(prototype) 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);
}
}

关于Javascript 模块模式、嵌套函数和子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11235991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com