【问题标题】:ES6: Why Symbol can not have another symbol as description?ES6:为什么符号不能有另一个符号作为描述?
【发布时间】:2025-12-01 23:55:01
【问题描述】:

我正在学习 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() 函数,我能够将符号转换为字符串。谁能详细说明发生了什么?谢谢。

【问题讨论】:

  • s 已经是Symbol

标签: javascript ecmascript-6 symbols


【解决方案1】:

为什么不让我使用现有符号作为描述

仅仅是因为所有的描述都必须是字符串,没有别的。

错误说它不能将符号转换为字符串,但是通过使用toString() 我可以将符号转换为字符串

是的,您可以显式将符号转换为字符串并使用toString 方法获取其描述。但是所有隐式转换都会抛出异常 - 这是一个deliberate feature,以防止我们意外使用非唯一描述而不是符号,例如使用属性键进行字符串连接时。

【讨论】:

最近更新 更多