是否可以提取符号的内容?

Is it possible to extract contents of a symbol?

我想制作一个将字符串映射到符号的字典,以便我可以为对象分配一个唯一的 "t" 属性,它始终指向一个唯一的符号。

我不知道如何从符号中取出符号内的原始字符串,以便我可以查找符号 table 来检查符号的有效性。

示例代码如下:

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);

我想知道是否可以在不使用正则表达式或创建包含字符串 "Box" 的新结构的情况下从符号 Symbol(Box) 中取出字符串 "Box"和符号 "Box"(这可能是最好的第二个解决方案)。

您应该在 Symbol 原语中使用 forkeyFor 成员 如果您将一个字符串传递给 for 方法,它会在全局注册表中搜索该字符串,如果发现该字符串已被注册,则会检索该字符串的值,否则会注册该字符串 keyFor 检索符号的值。将无效参数传递给 keyFor 将引发错误 >> Symbol.keyFor(arg) ,arg 必须是符号 例如

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

您的解决方案

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));

您不需要使用正则表达式。一个简单的 slice 就可以了:

console.log(Symbol("Box").toString().slice(7, -1)); // "Box"

这必须符合规范:

19.4.3.2 Symbol.prototype.toString ( )

  1. Let s be the this value.
  2. If Type(s) is Symbol, let sym be s.

  3. Return SymbolDescriptiveString(sym).

19.4.3.2.1 Runtime Semantics: SymbolDescriptiveString ( sym )

  1. Let desc be sym's [[Description]] value.
  2. If desc is undefined, let desc be the empty string.

  3. Return the result of concatenating the strings "Symbol(", desc, and ")".