Javascript Symbol Type Global Registry

Introduction

We can create and reuse symbols in a string-keyed global symbol registry using Symbol.for().

let fooGlobalSymbol = Symbol.for('foo'); 
console.log(typeof fooGlobalSymbol);  // "symbol" 

The first time Symbol.for() is called with a given string, it will check the global runtime registry.

If it finds that no symbol exists, it will generate a new symbol instance, and add it to the registry.

Additional invocations with the same string key will return that symbol instance.

let fooGlobalSymbol = Symbol.for('foo');          // creates new symbol 
let otherFooGlobalSymbol = Symbol.for('foo');     // reuses existing symbol 
            //from   w ww  .j ava2s . c om
console.log(fooGlobalSymbol === otherFooGlobalSymbol);  // true  

Symbols defined in the global registry are distinct from symbols created using Symbol(), even if they share a description:

let localSymbol = Symbol('foo'); 
let globalSymbol = Symbol.for('foo'); 
            /*w  ww  .jav  a 2s . co m*/
console.log(localSymbol === globalSymbol);  // false  

The global registry requires string keys.

The key used for the registry will also be used as the symbol description.

let emptyGlobalSymbol = Symbol.for(); 
console.log(emptyGlobalSymbol);   // Symbol(undefined) 

We can check against the global registry using Symbol.keyFor().

It accepts a symbol and will return the global string key for that global symbol, or undefined if the symbol is not a global symbol.

// Create global symbol 
let s = Symbol.for('foo'); 
console.log(Symbol.keyFor(s));   // foo 
            /*  www.  ja  v  a  2s.  c  om*/
// Create regular symbol 
let s2 = Symbol('bar'); 
console.log(Symbol.keyFor(s2));  // undefined 

Using Symbol.keyFor() with a non-symbol will throw a TypeError:

Symbol.keyFor(123);  // TypeError: 123 is not a symbol  



PreviousNext

Related