function fun1() { ... }
function fun2() { ... }
// 污染全局,極易命名衝突
var com = com || {};
com.zfanw = com.zfanw || {};
com.zfanw.module1 = (function() {
// 私有變量/函數
function privateFunc() { ... }
// 公開 API
return {
func1: function() { ... },
func2: function() { ... }
};
})();
com.zfanw.module2 = (function() { ... })();
// 調用
com.zfanw.module1.func1();
優點:減少全局變量。缺點:依賴管理手動、腳本加載順序敏感、無法按需加載。
(function($, mod1) {
mod1.func1.apply({}, ['arg1', 'arg2']);
})(jQuery, com.zfanw.module1);
// math.js
define(function() {
return {
add: function(a, b) { return a + b; }
};
});
// app.js (依賴 math)
define(['math'], function(math) {
console.log(math.add(1, 2)); // 3
});
<script data-main="scripts/main" src="require.js"></script>
require.config({
baseUrl: 'scripts',
paths: {
jquery: 'lib/jquery.min',
underscore: 'lib/underscore.min'
},
shim: {
'underscore': { exports: '_' }
}
});
require(['app'], function(app) {
// 應用啟動
});
r.js 合並壓縮部署。<!-- HTML -->
<script type="module">
import { add } from './math.js';
console.log(add(1,2));
</script>
// math.js
export function add(a, b) { return a + b; }
瀏覽器原生支持、靜態分析優化、Tree-shaking,是未來標準。