【发布时间】:2016-04-29 12:51:31
【问题描述】:
我一直在阅读命名空间、对象字面量、IIFE 等方面的内容,我试图了解以下哪一项是命名 JavaScript 代码的正确方法?
使用 IIFE 嵌套外部函数的命名空间
let myApp = myApp || {};
myApp.some_var = "someString";
myApp.some_func = (function(){ const some_const = 1;
let some_other_func = function(){
console.log(some_const);
};
return {
some_other_func: some_other_func
}
}());
myApp.another_func = (function(){ const another_const = 2;
let another_func = function(){
myApp.some_func.some_other_func();
};
return {
another_func: another_func
}
}());
具有嵌套外部函数的命名空间不使用 IIFE
let myApp = myApp || {};
myApp.some_var = "someString";
myApp.some_func = function(){ const some_const = 1;
let some_other_func = function(){
console.log(some_const);
};
return {
some_other_func: some_other_func
}
};
myApp.another_func = function(){ const another_const = 2;
let another_func = function(){
myApp.some_func.some_other_func();
};
return {
another_func: another_func
}
};
具有内部嵌套函数的命名空间
let myApp = (function() { let some_var = "someString";
let some_func = function(){
const some_const = 1;
let some_other_func = function(){
console.log(some_const);
};
return {
some_other_func: some_other_func
}
};
let another_func = function(){
const another_const = 2;
let another_func = function(){
some_func.some_other_func();
};
return {
another_func: another_func
}
};
return {
some_var: some_var,
some_func: some_func,
another_func: another_func
}
}());
IIFE 函数
let a_func = (function(){ let some_var = "someString"; }());
let some_func = (function(){ const some_const = 1;
let some_other_func = function(){
console.log(some_const);
};
return {
some_other_func: some_other_func
}
}(another_func, a_func));
let another_func = (function(){ const another_const = 2;
let another_func = function(){
some_func.some_other_func();
};
return {
another_func: another_func
}
}(a_func, some_func));
编辑:在我自己的特定示例中,代码将在 node.js 中运行,并且“应用程序”将少于 500 行代码,因此我计划将它们全部放在一个文件中。我对不建议使用 AMD、CommonJS、Browserify、Webpack、ES6 模块等的答案特别感兴趣。
【问题讨论】:
标签: javascript namespaces javascript-namespaces