模块化Javascript代码的两种方式

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 })();

 http://eloquentjavascript.net/1st_edition/

posted @ 2017-02-28 19:19  天琊蓝  阅读(190)  评论(0编辑  收藏  举报