示例工程 09-global-scripts-iife
09-global-scripts-iife/03-namespace/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>09 · 命名空间</title>
</head>
<body>
<p>打开 Console 查看命名空间的嵌套与重复加载行为。</p>
<script>
// 惯用法:window.NS = NS = {} —— 外层的 window.NS 兜底,内层的 NS 建立局部引用
var App = window.App = window.App || {};
App.Utils = App.Utils || {};
App.Utils.format = function (s) {
return '[' + s + ']';
};
App.Other = { alive: true };
</script>
<script>
// 第二个脚本再次执行同样的兜底:已有对象不会被清空
var App = window.App = window.App || {};
App.Utils = App.Utils || {};
window.__ns = {
keys: Object.keys(window.App),
utilsKeys: Object.keys(window.App.Utils),
formatted: window.App.Utils.format('x'),
otherAlive: window.App.Other.alive
};
</script>
<script type="module">
import { run } from './main.js';
run();
</script>
</body>
</html>