JavaScript 默認將變量掛載到 window 全局對象,多庫共存時極易發生命名衝突:
<script>
var isDoingWork = false; // 實際上是 window.isDoingWork = false
</script>
// 控制台可直接篡改
isDoingWork = true; // 污染全局狀態
// 引入第三方庫 Panacea.js 後
// 庫內部可能有:var isDoingWork = false; setInterval(() => isDoingWork = !isDoingWork, 3000);
// 導致你的業務邏輯異常,極難排查
模塊模式本質是封裝,將私有狀態隱藏在閉包中,僅暴露公共 API。IIFE (Immediately Invoked Function Expression) 提供閉包環境。
(function() {
// 私有作用域
var privateVar = 'secret';
function privateFn() { console.log(privateVar); }
// 暴露公共 API
window.MyModule = {
publicMethod: function() { privateFn(); }
};
})();
(function($, window, document) {
// $ 映射 jQuery,window/document 縮短查找鏈
var plugin = {
init: function() { $('body').append('<div>Ready</div>'); }
};
window.MyPlugin = plugin;
})(jQuery, window, document);
AngularJS 提供 angular.module 實現依賴注入與模塊管理,避免手寫 IIFE:
// app.js
angular.module('myApp', []) // 空數組表示無外部依賴
.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
// 控制器邏輯
$scope.loadData = function() {
$http.get('/api/data').then(function(res) {
$scope.items = res.data;
});
};
}]);
angular.module('myApp')
.factory('DataService', ['$http', '$q', function($http, $q) {
var cache = {}; // 私有緩存,外部不可直接訪問
return {
get: function(id) {
if (cache[id]) return $q.when(cache[id]);
return $http.get('/api/item/' + id).then(function(res) {
cache[id] = res.data;
return res.data;
});
},
clearCache: function() { cache = {}; }
};
}]);
angular.module('myApp')
.directive('userCard', function() {
return {
restrict: 'E',
scope: { user: '=' }, // 隔離作用域
templateUrl: 'templates/user-card.html',
link: function(scope, elem, attrs) {
// DOM 操作邏輯
}
};
});
ng-controller="MainCtrl as vm",避免 $scope 原型鏈陷阱Service 後綴,工廠用 Factory,常量用 Constantresolve 中預加載數據,控制器只負責展示$rootScope.$emit/$on 或專用 EventService 解耦組件通信src/
├── app/
│ ├── core/ # 核心模塊:配置、路由、攔截器
│ ├── shared/ # 共享組件:指令、過濾器、通用服務
│ ├── features/ # 業務模塊(按功能劃分)
│ │ ├── user/
│ │ │ ├── user.module.js
│ │ │ ├── user.controller.js
│ │ │ ├── user.service.js
│ │ │ └── user.directive.js
│ │ └── order/
│ └── app.module.js # 根模塊匯入所有子模塊
├── assets/
└── index.html
angular.module('modName', ['dep1', 'dep2']) 聲明依賴window.xxx 賦值模塊模式與 IIFE 是 JavaScript 模塊化的基石,AngularJS 將其內建為框架級能力。遵循「單一職責、依賴注入、隔離作用域」原則,配合合理的目錄結構,能構建出可維護、可測試、可擴展的 AngularJS 應用。即使遷移至 Angular/Vue/React,這套模塊化思維依然通用。