JS - modules

原生js我们怎么封装module

虽然现在各种module loader, requirjs, seajs, webpack, systemjs,es6

这次我们回归下,看看原生

我喜欢这种简单直接的,直接返回obj给个全局变量


var myGradesCalculate = (function () {

// Keep this variable private inside this closure scope
var myGrades = [93, 95, 88, 0, 55, 91];

// Expose these functions via an interface while hiding
// the implementation of the module within the function() block

return {
average: function () {
var total = myGrades.reduce(function (accumulator, item) {
return accumulator + item;
}, 0);

console.log('Your average grade is ');
},
xxx: myGrades,
failing: function () {
var failingGrades = myGrades.filter(function (item) {
return item < 70;
});
console.log('You failed ',failingGrades);

}
}
})();

调用模块直接来


myGradesCalculate.failing(); // 'You failed 2 times.'
myGradesCalculate.average(); // 'Your average grade is 70.33333333333333.'


console.log(myGradesCalculate.xxx)