// main.js —— 保留引用与 WeakMap:用可观察的模型说明差异 export function createRegistries() { const strong = new Map(); const weak = new WeakMap(); return { add(key, value) { strong.set(key, value); weak.set(key, value); }, strongSize() { return strong.size; }, hasWeak(key) { return weak.has(key); }, deleteStrong(key) { strong.delete(key); }, }; } export function attachListener(target, handler) { target.listeners ??= []; target.listeners.push(handler); return function detach() { const index = target.listeners.indexOf(handler); if (index >= 0) target.listeners.splice(index, 1); }; } export function simulateRetention({ listeners, cleaned }) { return cleaned ? 0 : listeners; } export function run(log = console.log) { const registries = createRegistries(); const keys = Array.from({ length: 1000 }, (_, i) => ({ id: i })); for (const key of keys) registries.add(key, { payload: 'x'.repeat(100) }); const target = { listeners: [] }; const off = attachListener(target, () => {}); attachListener(target, () => {}); log(`Map 保留条目:${registries.strongSize()}`); log(`WeakMap 能否查询某个键:${registries.hasWeak(keys[0])}`); log(`解绑前监听器数:${target.listeners.length}`); off(); log(`解绑后监听器数:${target.listeners.length}`); log('要点:Map 强引用键,WeakMap 不阻止回收且不可枚举;监听器要显式解绑。'); return { strong: registries.strongSize(), listeners: target.listeners.length }; }