我正在学习 Es6:Symbols 。我正在使用它并尝试使用另一个符号作为描述来创建一个符号:
var s = Symbol('foo');
console.log(s.toString()); //"Symbol(foo)"
var sS = Symbol(s); // <- thorws error
var sF = Symbol.for(s); // <- thorws error
console.log(s, sA);
我无法理解为什么它不允许我使用现有符号作为描述。当我运行上面的代码时,我看到以下控制台错误:
Uncaught TypeError: Cannot convert a Symbol value to a string
at Function.for (native)
由于错误表明它无法将符号转换为字符串。但正如您在代码(第 2 行)中看到的,通过使用 toString() 函数,我可以转换字符串中的符号。谁能详细说明发生了什么事吗?谢谢。
最佳答案
why is it not letting me use existing symbol as description
仅仅因为所有描述都必须是字符串,没有别的。
the error says that it can not convert the symbol to string, but by using
toString()
I am able to convert the symbol in string
是的,您可以显式将符号转换为字符串,并使用toString
方法获取其描述。但所有隐式转换都会引发异常 - 这是 deliberate feature防止我们意外地使用非唯一的描述而不是符号,例如当使用属性键进行字符串连接时。
关于javascript - ES6 : Why Symbol can not have another symbol as description?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107101/