在基于jQuery的Web应用程序中,我有各种脚本,其中可能包含多个文件,我一次只使用其中一个(我知道不包括所有这些都会更好,但我只是负责因为这不是我的决定)。所以我将每个文件包装在initModule()
函数中,该函数注册各种事件并进行一些初始化等。
现在我很好奇以下两种定义函数之间是否有任何差异,而不是混淆全局命名空间:
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
var somePrivateFunc = function() {
/* ... */
}
var anotherPrivateFunc = function() {
/* ... */
}
/* do some stuff here */
}
和
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
function somePrivateFunc() {
/* ... */
}
function anotherPrivateFunc() {
/* ... */
}
/* do some stuff here */
}
答案 0 :(得分:8)
这两种方法之间的主要区别在于功能何时可用。在第一种情况下,该功能在声明后变为可用,但在第二种情况下,它在整个范围内可用(称为提升)。
function init(){
typeof privateFunc == "undefined";
var privateFunc = function(){}
typeof privateFunc == "function";
}
function init(){
typeof privateFunc == "function";
function privateFunc(){}
typeof privateFunc == "function";
}
除此之外 - 它们基本相同。
答案 1 :(得分:0)
这是一个帮助我在javascript中管理模块的模型:
base.js:
var mod = {};
mod.functions = (function(){
var self = this;
self.helper1 = function() {
} ;
self.helper2 = function() {
} ;
return self;
}).call({});
module_one.js
mod.module_one = (function(){
var
//These variables keep the environment if you need to call another function
self = this, //public (return)
priv = {}; //private function
priv.funA = function(){
}
self.somePrivateFunc = function(){
priv.funA();
};
self.anotherPrivateFunc = function(){
};
// ini module
self.ini = function(){
self.somePrivateFunc();
self.anotherPrivateFunc();
};
// ini/end DOM
$(function() {
});
return self; // this is only if you need to call the module from the outside
// exmple: mod.module_one.somePrivateFunc(), or mod.module_one.ini()
}).call({});