2016-01-22 65 views
0

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

回答

0

恕我直言,最好的方法是使用CommonJS標準,從你的代碼我可以看出你已經是使用EcmaScript6,所以最好的方法是使用ES6 modules

在我自己的項目中,我使用browserify - 它允許我使用的NodeJS/CommonJS的模塊:由您提出

// module1.js 
exports.foo = function(value) { 
    return value + x; 
}; 

exports.CONST = 1; 

// module2.js 
var m1 = require('module1'); 
m1.foo(); 

所有的方法,大致相當,我個人喜歡revealing-module-pattern,並嘗試使用它時,我不能使用CommonJS。我也喜歡在模塊開始移動return語句,它有助於可讀性:

var MyModule = (function() { 
    'use strict'; 

    return { 
    foo: foo 
    }; 

    function foo() { 
    return 1; 
    } 
}()); 

另一個重要的問題是有封閉在IFFE整個模塊的代碼,尤其是當你使用strict mode和您連接js文件。

OK,這可能不是回答你的問題,但也許它幫助你看到更大的畫面...