javascript - ES6 : Why Symbol can not have another symbol as description?

标签 javascript ecmascript-6 symbols

我正在学习 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/

相关文章:

javascript - 使用纯 CSS 在响应式容器中垂直居中按钮?

javascript - 托管支付字段如何更改父 div 类?

javascript - 使用 jQuery 提交后清除表单

JavaScript 对数组进行过滤和减少以连接字符串

javascript - Object.assign什么时候会返回false

javascript - 使用解构赋值和 indexOf() 交换数组值

读取R中的csv文件,货币列为数字

javascript - 为什么我应该使用 & 而不是 &?

javascript - 如何获取所有具有固定起始字符串的html元素

architecture - 哪个符号代表分布式缓存?