示例工程 09-global-scripts-iife
09-global-scripts-iife/02-iife-module/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>09 · IIFE 模块模式</title>
</head>
<body>
<p>打开 Console 查看 IIFE 的私有状态与公开 API。</p>
<script>
// 经典写法:立即执行函数创建一个私有作用域,只把 API 挂到全局
var CounterModule = (function () {
var count = 0;
function inc() {
count += 1;
return count;
}
function reset() {
count = 0;
}
return {
inc: inc,
reset: reset,
get value() {
return count;
}
};
})();
</script>
<script>
// count 不在全局,外部拿不到;只能通过闭包里的方法访问
console.log('count in window =>', 'count' in window);
console.log('CounterModule keys =>', Object.keys(window.CounterModule));
</script>
<script type="module">
import { run } from './main.js';
run();
</script>
</body>
</html>