@@ -1428,7 +1428,92 @@ console.log(aGetFormatDate(dt));
14281428<!-- 1.这些代码中的函数必须是全局变量,才能暴露给使用方。全局变量污染 -->
14291429<!-- 2. a.js 知道要引用 a-util.js ,但是他知道还需要依赖于util.js吗? -->
14301430` ` `
1431+ #### 使用模块化
14311432
1433+ ` ` ` JavaScript
1434+ //util.js
1435+ export{
1436+ getFormatDate:function (data,type) {
1437+ //type === 1 返回 2017-06-15
1438+ //type === 2 返回 2017年6月15日 格式
1439+ }
1440+ }
1441+ //a-util.js
1442+ var getFormatDate = require('util.js');
1443+ export{
1444+ aGetFormatDate:function (date) {
1445+ //要求返回 2017年6月15日 格式
1446+ return getFormatDate(date,2);
1447+ }
1448+ }
1449+ // a.js
1450+ var aGetFormatDate = require('a-util.js')
1451+ var dt = new Date();
1452+ console.log(aGetFormatDate(dt));
1453+
1454+ //直接‘<script src="a.js"></script>’,其他的根据依赖关系自动引用
1455+ //那两个函数,没必要做成全局变量,不会带来污染和覆盖
1456+ ` ` `
1457+ #### AMD
1458+ * require .js ` requirejs.org/`
1459+ * 全局define函数
1460+ * 全局require函数
1461+ * 依赖JS 会自动、异步加载
1462+
1463+ ` ` ` JavaScript
1464+ //util.js
1465+ define(function () {
1466+ return{
1467+ getFormatDate: function (date,type) {
1468+ if (type === 1) {
1469+ return '2017-06-15'
1470+ }
1471+ if (type === 2) {
1472+ return '2017年6月15日'
1473+ }
1474+ }
1475+ }
1476+ });
1477+
1478+ //a-util.js
1479+ define(['./util.js'],function (util) {
1480+ return{
1481+ aGetFormatDate: function (date) {
1482+ return util.getFormatDate(date,2);
1483+ }
1484+ }
1485+ });
1486+
1487+ // a.js
1488+ define('[./a-util.js]',function (aUtil) {
1489+ return{
1490+ printDate:function (date) {
1491+ console.log(aUtil.aGetFormatDate);
1492+ }
1493+ }
1494+ });
1495+
1496+ //main.js
1497+ require('[./a.js]',function (a) {
1498+ var date = new Date();
1499+ a.printDate(date);
1500+ });
1501+ ` ` `
1502+ * 使用
1503+
1504+ ` ` ` html
1505+ <!DOCTYPE html>
1506+ <html>
1507+ <head>
1508+ <meta charset="utf-8">
1509+ <title>Document</title>
1510+ </head>
1511+ <body>
1512+ <p>AMD test</p>
1513+ <script src="/require.min.js" data-main="./main.js"></script>
1514+ </body>
1515+ </html>
1516+ ` ` `
14321517-- -
14331518
14341519### JSDemo JS 小程序
0 commit comments