Symbol
一句话解释
Symbol 是 primitive 值 那个 是 guaranteed 到 是 唯一, 经常 used as 对象 属性 键 到 avoid collisions.
用大白话说
Symbol 是 primitive 类型 introduced in ES6. 每个 Symbol 是唯一 — Symbol('x') === Symbol('x') is false even with the same description. This makes Symbols ideal for creating non-colliding object property keys.
Symbols are often used to add 'hidden' properties to objects that won't conflict with other properties or show up in normal iteration. Well-known Symbols (like Symbol.iterator and Symbol.toPrimitive) define core language behaviors — for example, Symbol.iterator makes an object iterable.
Symbols do not show up in for...in loops or 对象.键(). To access them, use 对象.getOwnPropertySymbols(). To create a shared symbol across code, use Symbol.for('键') (the global symbol registry).
示例
const s1 = Symbol("id");
const s2 = Symbol("id");
console.log(s1 === s2); // false — unique
const obj = { [s1]: "secret" };
console.log(Object.keys(obj)); // [] — symbol hidden每个 Symbol 是 唯一. Symbol-keyed 属性 don't appear in 对象.键.
相关术语
相关资源
相关课程
- 数据 类型
学习 关于 Symbols.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。