Thi*_*ter 6 javascript scope private-functions
在基于jQuery的Web应用程序中,我有各种脚本,其中可能包含多个文件,我一次只使用其中一个(我知道不包括所有这些都会更好,但我只负责JS所以这不是我的决定).所以我将每个文件包装在一个函数中,该函数注册各种事件并进行一些初始化等.initModule()
现在我很好奇以下两种定义函数之间是否存在任何差异,而不是混淆全局命名空间:
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
var somePrivateFunc = function() {
/* ... */
}
var anotherPrivateFunc = function() {
/* ... */
}
/* do some stuff here */
}
Run Code Online (Sandbox Code Playgroud)
和
function initStuff(someArg) {
var someVar = 123;
var anotherVar = 456;
function somePrivateFunc() {
/* ... */
}
function anotherPrivateFunc() {
/* ... */
}
/* do some stuff here */
}
Run Code Online (Sandbox Code Playgroud)
这两种方法之间的主要区别在于功能何时可用.在第一种情况下,该功能在声明后变为可用,但在第二种情况下,它在整个范围内可用(称为提升).
function init(){
typeof privateFunc == "undefined";
var privateFunc = function(){}
typeof privateFunc == "function";
}
function init(){
typeof privateFunc == "function";
function privateFunc(){}
typeof privateFunc == "function";
}
Run Code Online (Sandbox Code Playgroud)
除此之外 - 它们基本相同.
| 归档时间: |
|
| 查看次数: |
1554 次 |
| 最近记录: |