Symbol() 构造函数
Symbol()
函数返回 Symbol 类型的原始值。
¥The Symbol()
function returns primitive values of type Symbol.
Try it
语法
参数
示例
创建符号
¥Creating symbols
要创建新的原始符号,请编写 Symbol()
并使用可选字符串作为其描述:
¥To create a new primitive symbol, you write Symbol()
with an optional
string as its description:
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:
Symbol("foo") === Symbol("foo"); // false
新符号()
¥new Symbol()
¥The following syntax with the new
operator will throw a
TypeError
:
const sym = new Symbol(); // TypeError
这会阻止作者创建显式 Symbol
封装器对象而不是新的符号值,并且可能会令人惊讶,因为通常可以围绕原始数据类型创建显式封装器对象(例如 new Boolean
、new String
和 new 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:
const sym = Symbol("foo");
const symObj = Object(sym);
typeof sym; // "symbol"
typeof symObj; // "object"
规范
Specification |
---|
ECMAScript Language Specification # sec-symbol-constructor |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also