示例工程 09-global-scripts-iife
09-global-scripts-iife/03-namespace/main.js
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
// main.js —— 命名空间:用嵌套对象减少全局名字数量
// window.NS = window.NS || {} 的语义:只在不存在时创建,重复加载不覆盖已有内容。
export function ensureNamespace(root, path) {
let current = root;
for (const key of path.split('.')) {
const value = current[key];
if (!value || typeof value !== 'object' || Array.isArray(value)) {
current[key] = {};
}
current = current[key];
}
return current;
}
export function run(log = console.log) {
if (typeof window === 'undefined') {
throw new Error('本示例需要浏览器环境:请通过 index.html 打开');
}
const snapshot = window.__ns || {};
log(`App 的键:${(snapshot.keys || []).join(', ')}`);
log(`App.Utils 的键:${(snapshot.utilsKeys || []).join(', ')}`);
log(`App.Utils.format('x'):${snapshot.formatted}`);
log(`App.Other 是否保留:${snapshot.otherAlive}`);
log('嵌套命名空间把多个全局名字收敛到一个入口,但仍然共享、仍然可变。');
return snapshot;
}