Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

javascript - What is 'global symbol registry'?

var sym = Symbol();

is window['sym'] which is already global scope.

But MDN says:

The above syntax using the Symbol() function will not create a global symbol that is available in your whole codebase. To create symbols available across files and in a global scope-like environment, use the methods Symbol.for() and Symbol.keyFor() to set and retrieve symbols from the global symbol registry.

sym is already in global scope in a browser, with above declaration syntax.

What is global symbol registry?

Each html document is tied with window object.

So, In a browser world, How does this scope of symbol availability across files/realms different from global scope(window object)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var sym = Symbol();

is creating a new property sym in dictionary(window), which is in global scope, where value can be accessed as window['sym'].

Well, no. It does create a symbol and assigns it to a local variable named sym. Only if you are executing this code in the global scope (which you usually wouldn't, for modularity) it does create a property on the global object of your realm (js environment). Notice that this global object is not always window like in web pages, it depends on your environment.

What is global symbol registry?

It's a registry (think: dictionary) for symbols that you can access via a string key. And "global" does in this case mean even more global than a global scope, the global symbol registry does span all realms of your engine. In a browser, the web page, an iframe, and web worker would all have their own realm with own global objects, but they could share symbols via this global registry.

And this sharing is exactly the purpose. If you'd otherwise put

var sym1 = Symbol("shared");

var sym2 = Symbol("shared");

in two places, then sym1 !== sym2. If you've got a shared object, using the symbols as property keys would create two different properties. If however you do

var sym1 = Symbol.for("shared");

var sym2 = Symbol.for("shared");

then sym1 === sym2 and when you use it you'll always get the same property.

See also Crossing realms with symbols on 2ality and Symbols and why they're awesome for more examples, including the well-known symbols which are similarly global.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...