我一直在阅读关于命名空间,对象文字,IIFE等,我试图理解以下哪个是命名空间JavaScript代码的正确方法?如何使用或不使用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模块等。