在基于jQuery的Web应用程序中,我有各种各样的脚本,其中可能包含多个文件,而我一次只使用其中一个(我知道不包括所有文件会更好,但是我只负责JS因此,这不是我的决定)。因此,我将每个文件包装在initModule()
函数中,该函数注册各种事件并进行一些初始化等操作。
现在,我很好奇以下两种定义函数的方式之间是否有区别,这些方式不会使全局 namespace 困惑:
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 */
}
最佳答案
这两种方法之间的主要区别在于该功能何时可用。在第一种情况下,该功能在声明后可用,而在第二种情况下,该功能在整个范围内都可用(称为提升)。
function init(){
typeof privateFunc == "undefined";
var privateFunc = function(){}
typeof privateFunc == "function";
}
function init(){
typeof privateFunc == "function";
function privateFunc(){}
typeof privateFunc == "function";
}
除此之外-它们基本相同。