← 中文资源

简体中文版本

Symbol 键对 Object.keys 与 JSON 隐身

Symbol 键对 Object.keys、for..in 与 JSON.stringify 全部隐身,只有 getOwnPropertySymbols 与 Reflect.ownKeys 能枚举,库挂内部元数据不会被序列化带出去。

阅读英文原文

运行结果

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

Object.keys: ["name"]
JSON.stringify: {"name":"adapter"}
own symbols: id
Reflect.ownKeys entries: 2
symbol value still readable: 43

实现说明

顶层就这几处状态:id、record。 顶层对象字面量把 name 定成普通值——没有派生,背后也没有导入。

使用要点

  • 跑完文件,输出里会留下标记——Object.keys:、JSON.stringify:、own symbols:。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件用顶层绑定保存自己的状态:id、record。

核心语句

.map((s) => s.description)
.join(','),
);

代码示例

// Symbol property keys are invisible to every enumeration mechanism by default: Object.keys, for..in, and JSON.stringify all miss them
const id = Symbol('id');
const record = { name: 'adapter', [id]: 42 };

console.log('Object.keys:', JSON.stringify(Object.keys(record)));
console.log('JSON.stringify:', JSON.stringify(record));

// Listing Symbol keys explicitly: only these two APIs can see them
console.log(
  'own symbols:',
  Object.getOwnPropertySymbols(record)
    .map((s) => s.description)
    .join(','),
);
console.log('Reflect.ownKeys entries:', Reflect.ownKeys(record).length);

// This is why libraries hang internal metadata on Symbols: serialization never leaks it
record[id] = 43;
console.log('symbol value still readable:', record[id]);