← 中文资源

简体中文版本

Symbol.for 经全局注册表共享符号

Symbol.for('key') 查进程级注册表,两个模块拿到同一个符号,隐藏元数据落在同一个键上;keyFor 能读回键名,非注册符号没有键。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

true
false
rate-limiter
undefined
3

实现说明

各个操作都建立在顶层绑定之上: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);