Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...