1.将模块整体放在函数里
1 function buildMonthNameModule() { 2 var names = ["January ", "February", "March", "April", "May ", "June ", "July", "August ", "September ", "October ", "November", "December"]; 3 function getMonthName(number) { 4 return names[number]; 5 } 6 function getMonthNumber(name) { 7 for (var number = 0; number < names.length; number++) { 8 if (names[number] == name) { 9 return number; 10 } 11 } 12 } 13 window.getMonthName = getMonthName; 14 window.getMonthNumber = getMonthNumber; 15 } 16 buildMonthNameModule();
2.模块对象
1 var days = (function() { 2 var names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; 3 return { 4 getDayName: function(number) { 5 return names[number]; 6 }, 7 getDayNumber: function(name) { 8 for (var number = 0; number < names.length; number++) { 9 if (names[number] == name) { 10 return number; 11 } 12 } 13 } 14 }; 15 })();