Symbols
唯一, 不可变 identifiers used for 隐藏属性 and well-known iteration protocols.
你将学到
- 什么 Symbol 是 and 为什么每个 Symbol() 是唯一
- Using Symbols as 对象键 到 avoid collisions
- Symbols 是不 enumerated 通过 for...in or 对象.键
- Shared Symbols 使用 Symbol.for and Symbol.keyFor
- Well-known Symbols 如 Symbol.iterator and Symbol.toPrimitive
概念讲解
Unique Identifiers
Symbol 是一种 primitive type introduced in ES6. Every call to Symbol() produces a completely unique value — even Symbol("foo") === Symbol("foo") is false. The optional description is just a label for debugging; it does not affect identity. This uniqueness makes Symbols ideal as property keys that will never accidentally collide with another key.
Symbols as Object Keys
You can use a Symbol as a property key in an object: obj[mySymbol] = 值. Symbol-keyed properties are hidden from normal enumeration — for...in, 对象.键(), and JSON.stringify() all skip them. This lets you attach metadata to an object without it appearing in serialization or iteration. To access Symbol keys explicitly, use 对象.getOwnPropertySymbols().
Shared Symbols
Symbol.for("键") returns a global, shared Symbol: calling it again with the same key returns the same Symbol. This is the global Symbol registry. Symbol.keyFor(sym) retrieves the key for a shared Symbol. Use Symbol.for when you need cross-module sharing (e.g., a library-defined extension point); use Symbol() for private, local keys.
Well-Known Symbols
JavaScript defines a set of well-known Symbols on the Symbol object that hook into language behavior. Symbol.iterator defines how for...的 and the spread operator iterate an object. Symbol.toPrimitive controls conversion to number/string/boolean. Symbol.hasInstance customizes instanceof. Symbol.toStringTag improves 对象.原型.toString output. Implementing these on your objects lets you integrate deeply with the language.
Practical Use
Symbols are not an everyday tool, but they appear in library internals and protocol definitions. If you are building a framework, Symbols let you define extension points that users cannot accidentally overwrite. If you are consuming APIs, you will encounter them on iterators and other built-in protocols. Knowing they exist helps you read framework source code and understand why certain properties do not show up in 对象.键().
示例代码
// Every Symbol() is unique, even with the same description
const s1 = Symbol("id");
const s2 = Symbol("id");
console.log(s1 === s2); // false
console.log(s1.description); // "id" — just a debug label
// Symbols as hidden object keys
const hidden = Symbol("private");
const obj = {
name: "Ada",
[hidden]: "secret metadata",
};
console.log(Object.keys(obj)); // ["name"] — Symbol key is hidden
console.log(JSON.stringify(obj)); // {"name":"Ada"} — not serialized
console.log(obj[hidden]); // "secret metadata" — accessible directly
console.log(Object.getOwnPropertySymbols(obj)); // [Symbol(private)]
// Shared Symbols across modules via the global registry
const SHARED = Symbol.for("app.shared");
const objA = { [SHARED]: "from module A" };
const sameSymbol = Symbol.for("app.shared");
console.log(objA[sameSymbol]); // "from module A"
console.log(Symbol.keyFor(SHARED)); // "app.shared"
// Well-known Symbol: customize toString output
class Color {
constructor(hex) {
this.hex = hex;
}
get [Symbol.toStringTag]() {
return "Color";
}
}
console.log(Object.prototype.toString.call(new Color("#fff"))); // "[object Color]"
// Well-known Symbol: control primitive conversion
const temp = {
value: 42,
[Symbol.toPrimitive](hint) {
if (hint === "number") return this.value;
if (hint === "string") return `${this.value}°`;
return this.value;
},
};
console.log(+temp); // 42 (number hint)
console.log(`${temp}`); // "42°" (string hint)
Shows Symbol uniqueness, 隐藏键 不可见到 对象.键 and JSON, 全局 registry 使用 Symbol.for, toStringTag customization, and toPrimitive for controlling +temp and 字符串 interpolation.
动手试一试
- JSON Formatter
See 如何 Symbol-keyed 属性是 skipped 通过 JSON.stringify.
- JSON 树 Viewer
Inspect 对象 and notice Symbol 属性是 不 enumerated.
常见错误
错误写法
Expecting Symbol('x') === Symbol('x') 到是 真
正确做法
Symbol() 总是返回唯一值. 描述是 仅调试 label. For shared Symbols 跨越模块, use Symbol.for('x') 哪个返回相同 Symbol for 相同键 从全局 registry.
错误写法
Looking for Symbol-keyed 属性使用对象.键 or for...in
正确做法
Symbol 键是 隐藏从 对象.键, for...in, and JSON.stringify. Use 对象.getOwnPropertySymbols(obj) 到 retrieve 它们, or Reflect.ownKeys for 两者都字符串 and Symbol 键.
相关资源
相关速查表
- JavaScript Cheatsheet
Symbol creation, shared registry, and well-known Symbols.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。