前言
JavaScript 基础
1
2
3
4
5
6
7
8
|
<html>
<head>
<script type=
"text/javascript"
src=
"index.js"
></script>
</head>
<body>
<p id=
"hello"
> Hello Wrold </p>
<input type=
"button"
onclick=
"onPress()"
value=
"Click me"
/>
</body></html>
|
1
2
3
|
// index.jsfunction onPress() { var p = document.getElementById('hello');
p.innerHTML =
'Hello bestswifter'
;
}
|
1
2
|
// math.jsfunction add(a, b) { return a + b;
}
|
1
2
3
|
// index.jsimport "math.js"function onPress() { var p = document.getElementById('hello');
p.innerHTML = add(1, 2);
}
|
1
2
3
4
5
6
7
8
9
|
<html>
<head>
<script type=
"text/javascript"
src=
"index.js"
></script>
<script type=
"text/javascript"
src=
"math.js"
></script>
</head>
<body>
<p id=
"hello"
> Hello Wrold </p>
<input type=
"button"
onclick=
"onPress()"
value=
"Click me"
/>
</body></html>
|
1
2
3
|
// index.jsfunction onPress() { var p = document.getElementById('hello');
p.innerHTML = add(1, 2);
}
|
初步模块化
-
index.js 无法 import,依赖于 HTML 的引用
-
index.js 中无法对 add 方法的来源做区分,缺少命名空间的概念
1
2
3
4
5
6
7
|
//index.js function onPress() { var p = document.getElementById('hello');
p.innerHTML = math.add(1, 2);
}
//math.jsvar math = {
base: 0,
add:
function
(a, b) {
return
a + b + base;
},
};
|
1
2
3
4
5
|
// math.jsvar math = (function() { var base = 0; return {
add:
function
(a, b) {
return
a + b + base;
},
};
})();
|
1
|
// global.jsvar module = { exports: {}, // 用来存储所有暴露的内容};
|
1
2
3
4
5
|
var
math = (
function
() {
var
base = 0;
return
{
add:
function
(a, b) {
return
a + b + base;
},
};
})();module.exports.math = math;
|
1
2
3
|
var
math = module.exports.math;
function
onPress() {
var
p = document.getElementById(
'hello'
);
// math
p.innerHTML = math.add(1, 2);
}
|
现有模块化方案
CommonJS
AMD
1
2
3
4
|
require([
'myModule1'
,
'myModule2'
],
function
(m1, m2){
// 主回调逻辑
m1.printName();
m2.printName();
});
|
CMD
1
2
3
4
5
6
|
define(
function
(require, exports, module) {
var
foo = require(
'foo'
);
// 同步
foo.add(1, 2);
... require.async(
'math'
,
function
(math) {
// 异步
math.add(1, 2);
});
});
|