Symbol() 构造函数

Symbol() 函数返回 Symbol 类型的原始值。

¥The Symbol() function returns primitive values of type Symbol.

Try it

语法

¥Syntax

js
Symbol()
Symbol(description)

注意:没有 new 只能调用 Symbol()。尝试用 new 构造它会抛出 TypeError

¥Note: Symbol() can only be called without new. Attempting to construct it with new throws a TypeError.

参数

¥Parameters

description Optional

一根绳子。符号的描述,可用于调试但不能访问符号本身。

示例

¥Examples

创建符号

¥Creating symbols

要创建新的原始符号,请编写 Symbol() 并使用可选字符串作为其描述:

¥To create a new primitive symbol, you write Symbol() with an optional string as its description:

js
const sym1 = Symbol();
const sym2 = Symbol("foo");
const sym3 = Symbol("foo");

上面的代码创建了三个新符号。请注意,Symbol("foo") 不会将字符串 "foo" 强制转换为符号。它每次都会创建一个新符号:

¥The above code creates three new symbols. Note that Symbol("foo") does not coerce the string "foo" into a symbol. It creates a new symbol each time:

js
Symbol("foo") === Symbol("foo"); // false

新符号()

¥new Symbol()

以下带有 new 运算符的语法将抛出 TypeError

¥The following syntax with the new operator will throw a TypeError:

js
const sym = new Symbol(); // TypeError

这会阻止作者创建显式 Symbol 封装器对象而不是新的符号值,并且可能会令人惊讶,因为通常可以围绕原始数据类型创建显式封装器对象(例如 new Booleannew Stringnew Number)。

¥This prevents authors from creating an explicit Symbol wrapper object instead of a new symbol value and might be surprising as creating explicit wrapper objects around primitive data types is generally possible (for example, new Boolean, new String and new Number).

如果你确实想创建 Symbol 封装对象,可以使用 Object() 函数:

¥If you really want to create a Symbol wrapper object, you can use the Object() function:

js
const sym = Symbol("foo");
const symObj = Object(sym);
typeof sym; // "symbol"
typeof symObj; // "object"

规范

Specification
ECMAScript Language Specification
# sec-symbol-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看