Dmitry Dmitry - 7 days ago 7
Javascript Question

Is it possible to extract contents of a symbol?

I want to make a dictionary mapping Strings to Symbols so that I can assign to objects a unique "t" property that always points to a unique symbol.

I can't figure out how to get the original string inside the symbol back out of the symbol so that I can look up the Symbol table to check validity of the symbol.

Here's the sample code:

var t = {
'Box': Symbol("Box")
};

var Box = (function() {
var Box = function(x) {
this.t = t['Box'];
this.x = x;
};

return Box;
})();

var q = new Box(2);
console.log(q);
console.log(q.t);


I want to know if it is possible to get the string "Box" back out of the symbol Symbol(Box) without using regular expressions or creating a new structure which contains both the string "Box" and the Symbol "Box"(which is probably the best second solution).

Answer

You should use the for and keyFor member in the Symbol Primitive if you pass in a string into the for method it searches a global registory for that string, if it finds that the string has already been registered it retrieves the value of the string or else it registers the string keyFor retrieves the value of the symbol. Passing an invalid argument to keyFor will throw an error >> Symbol.keyFor(arg) , arg must be a symbol e.g

'use strict';
let myName = Symbol.for('victory');
console.log(Symbol.keyFor(myName));  // 'victory'

Your solution

var t = {
 'Box': Symbol.for("Box")
};

var Box = (function() {
  var Box = function(x) {
     this.t = t['Box'];
     this.x = x;
 };

  return Box;
})();

var q = new Box(2);
console.log(q);
console.log(Symbol.keyFor(q.t));
Comments