实现说明
各个操作都建立在顶层绑定之上:local、shared、again、requestMeta。
一个对象字面量承载 url——每个值都就地写死。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 状态都挂在模块顶层:local、shared、again。
核心语句
const requestMeta = Symbol.for('app.requestMeta');
const shared = Symbol.for('rate-limiter');
const again = Symbol.for('rate-limiter');
代码示例
// Symbol() mints a brand-new symbol on every call
const local = Symbol('rate-limiter');
// Symbol.for('key') consults a process-wide registry: every module
// asking for the same key shares one symbol, so cross-module
// metadata lands on the same property
const shared = Symbol.for('rate-limiter');
const again = Symbol.for('rate-limiter');
console.log(shared === again);
console.log(local === shared);
// keyFor reads the registry key back; non-registry symbols have none
console.log(Symbol.keyFor(shared));
console.log(Symbol.keyFor(local));
// Practical shape: hidden metadata keyed by a shared registry symbol
const requestMeta = Symbol.for('app.requestMeta');
const request = { url: '/orders' };
request[requestMeta] = { retriedAt: 3 };
console.log(request[requestMeta].retriedAt);