我一直在閱讀關於命名空間,對象文字,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模塊等。