- 不使用模塊化
- util.js getFormatDate函數(shù) 最底層的函數(shù)
- a-util.js aGetFormatDate 使用依賴getFormatDate (業(yè)務(wù)層的底層)
- a.js aGetFormatDate (a業(yè)務(wù))一層一層的引用
代碼如下:
// util.js
function getFormatDate(date,type){
// type === 1 返回 2017-06-15
// type === 2 返回 2017年06月15日格式
// ...
}
// a-util.js
function aGetFormatDate(date){
//要求返回 2017年6月15日 格式
return getFormatDate(date,2)
}
// a.js
var dt = new Date()
console.log(aGetFormatDate(dt))
使用
<script src="util.js"></script>
<script src="a-util.js"></script>
<script src="a.js"></script>
<!--1.這些代碼中的函數(shù)必須是全局變量,才能暴露給使用方。全局變量污染-->
<!--2.a.js 知道要引用 a-util.js,但是他知道還需要依賴于util.js嗎?-->
依賴關(guān)系根本不清楚,如果順序錯了,會報錯。
- 使用模塊化(設(shè)計一種理想狀態(tài),不一定能實現(xiàn))
//util.js
export {
getFormatDate:function(date,type){
// type === 1 返回 2017-06-15
// type === 2 返回 2017年06月15日格式
// ...
}
}
// a-util.js
var getFormatDate = require('util.js')
export {
aGetFormatDate: function(date){
//要求返回 2017年6月15日 格式
return getFormatDate(date,2)
}
}
//a.js
var aGetFormatDate=require('a-util.js')
var dt=new Date()
console.log(aGetFormatDate(dt))
// 直接'<script src="a.js"></script>',其他的根據(jù)依賴關(guān)系自動引用
//那兩個函數(shù),沒必要做成全局變量,不會嗲來污染和覆蓋
AMD
- require.js requirejs.org/
- 全局define函數(shù)
- 全局require函數(shù)
- 依賴js會自動、異步加載
使用require.js
//util.js
define(
function() {
getFormatDate: function(date, type) {
// type === 1 返回 2017-06-15
// type === 2 返回 2017年06月15日格式
// ...
}
}
)
// a-util.js
define(
[. / util.js],
function(util) {
return {
aGetFormatDate: function(date) {
//要求返回 2017年6月15日 格式
return getFormatDate(date, 2)
}
}
}
)
// a.js
define(
[. / a - util.js],
function(autil) {
return {
printDate: function(date) {
console.log(aUtil.aGetFormatDate(date))
}
}
}
)
// main.js
require(
['./a.js'],
function(a) {
var date = new Date()
a.printDate(date);
}
)
使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<script src="./require.min.js" data-main="./main.js"></script>
</body>
</html>
AMD示例
AMD示例