Symbol.keyFor()工作原理?为何第二种场景无法获取标识字符串?
First, let's break down how Symbol.keyFor() actually works:
- Symbols in JavaScript have two distinct creation paths:
Symbol.for('key'): This creates (or fetches an existing) symbol that gets stored in the global symbol registry — a shared, cross-scope storage space for symbols made with this method.Symbol('key'): This generates a unique, local symbol that is never added to the global registry. The string you pass here is just a debugging description, not a key tied to a registry entry.
Symbol.keyFor(symbol) does one specific thing: it checks the global symbol registry for the provided symbol. If the symbol exists in the registry, it returns the associated string key; if not, it returns undefined.
Now let's walk through your code example step by step:
let obj = { [Symbol('my_key')]: 1, enum: 2, nonEnum: 3 } document.write(Symbol.keyFor(Symbol.for('my_key')) + '<br>'); // retrieves 'my_key' document.write(Symbol.keyFor(Object.getOwnPropertySymbols(obj)[0])); // does not retrieve 'my_key'
Why the first call works
Symbol.for('my_key') creates a symbol in the global registry, linked directly to the key 'my_key'. When you pass this symbol to Symbol.keyFor(), it finds the matching entry in the registry and returns the key as expected.
Why the second call returns undefined
Object.getOwnPropertySymbols(obj)[0] gives you the symbol created with Symbol('my_key'). Since this symbol was made with the plain Symbol() constructor, it was never added to the global symbol registry. Symbol.keyFor() can't locate it in the registry, so it returns undefined — even though the symbol has the same description string as the registry-based one.
内容的提问来源于stack exchange,提问作者overexchange

