I have been reading up on namespacing, Object literals, IIFEs, etc. and I'm trying to understand which of the following is the right way to namespace JavaScript code?
Namespace with nested external functions using 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
}
}());
Namespace with nested external functions not using 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
}
};
Namespace with internal nested functions
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 functions
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));
Edit: In my own particular example the code will be running in node.js and the "application" will be less than 500 lines of code so I'm planning on having it all in one file. I'm particularly interested in answers that don't suggest using AMD, CommonJS, Browserify, Webpack, ES6 Modules, etc.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…