Symbol

The data type symbol primitive data type Symbol() function returns a value of type symbol , has static properties that expose several members of built-in objects, has static methods that expose the global symbol registry, and resembles a built-in object class, but is incomplete as a constructor because it does not support the syntax " new Symbol() ".

Every symbol value returned from Symbol() is unique.  A symbol value may be used as an identifier for object properties; this is the data type's primary purpose, although other use-cases exist, such as enabling opaque data types, or serving as an implementation-supported unique identifier in general.  Some further explanation about purpose and usage can be found in the glossary entry for Symbol .

描述

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

let sym1 = Symbol()
let sym2 = Symbol('foo')
let sym3 = Symbol('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
					

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

let sym = new Symbol()  // TypeError
					

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 ).

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

let sym = Symbol('foo')
typeof sym      // "symbol"
let symObj = Object(sym)
typeof symObj   // "object"
					

Shared symbols in the global symbol registry

The above syntax using the Symbol() function will not create a global symbol that is available in your whole codebase. To create symbols available across files and even across realms (each of which has its own global scope), use the methods Symbol.for() and Symbol.keyFor() to set and retrieve symbols from the global symbol registry.

Finding symbol properties on objects

The method Object.getOwnPropertySymbols() returns an array of symbols and lets you find symbol properties on a given object. Note that every object is initialized with no own symbol properties, so that this array will be empty unless you've set symbol properties on the object.

构造函数

Symbol()
创建新的 Symbol object. It is incomplete as a constructor because it does not support the syntax " new Symbol() ".

静态特性

Symbol.asyncIterator
A method that returns the default AsyncIterator for an object. Used by for await...of .
Symbol.hasInstance
A method determining if a constructor object recognizes an object as its instance. Used by instanceof .
Symbol.isConcatSpreadable
A Boolean value indicating if an object should be flattened to its array elements. Used by Array.prototype.concat() .
Symbol.iterator
A method returning the default iterator for an object. Used by for...of .
Symbol.match
A method that matches against a string, also used to determine if an object may be used as a regular expression. Used by String.prototype.match() .
Symbol.matchAll
A method that returns an iterator, that yields matches of the regular expression against a string. Used by String.prototype.matchAll() .
Symbol.replace
A method that replaces matched substrings of a string. Used by String.prototype.replace() .
Symbol.search
A method that returns the index within a string that matches the regular expression. Used by String.prototype.search() .
Symbol.split
A method that splits a string at the indices that match a regular expression. Used by String.prototype.split() .
Symbol.species
A constructor function that is used to create derived objects.
Symbol.toPrimitive
A method converting an object to a primitive value.
Symbol.toStringTag
A string value used for the default description of an object. Used by Object.prototype.toString() .
Symbol.unscopables
An object value of whose own and inherited property names are excluded from the with environment bindings of the associated object.

静态方法

Symbol.for(key)
Searches for existing symbols with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with key .
Symbol.keyFor(sym)
Retrieves a shared symbol key from the global symbol registry for the given symbol.

实例特性

Symbol.prototype.description
A read-only string containing the description of the symbol.

实例方法

Symbol.prototype.toSource()
Returns a string containing the source of the Symbol object. Overrides the Object.prototype.toSource() 方法。
Symbol.prototype.toString()
Returns a string containing the description of the Symbol. Overrides the Object.prototype.toString() 方法。
Symbol.prototype.valueOf()
Returns the primitive value of the Symbol object. Overrides the Object.prototype.valueOf() 方法。
Symbol.prototype[@@toPrimitive]
Returns the primitive value of the Symbol 对象。

范例

Using the typeof operator with symbols

typeof operator can help you to identify symbols.

typeof Symbol() === 'symbol'
typeof Symbol('foo') === 'symbol'
typeof Symbol.iterator === 'symbol'
					

Symbol type conversions

Some things to note when working with type conversion of symbols.

  • When trying to convert a symbol to a number, a TypeError will be thrown
    (e.g. + sym or sym | 0 ).
  • When using loose equality, Object( sym ) == sym 返回 true .
  • Symbol("foo") + "bar" throws a TypeError (can't convert symbol to string). This prevents you from silently creating a new string property name from a symbol, for example.
  • "safer" String( sym ) conversion works like a call to Symbol.prototype.toString() with symbols, but note that new String( sym ) will throw.

Symbols and for...in iteration

Symbols are not enumerable in for...in iterations. In addition, Object.getOwnPropertyNames() will not return symbol object properties, however, you can use Object.getOwnPropertySymbols() to get these.

let obj = {}
obj[Symbol('a')] = 'a'
obj[Symbol.for('b')] = 'b'
obj['c'] = 'c'
obj.d = 'd'
for (let i in obj) {
   console.log(i)  // logs "c" and "d"
}
					

Symbols and JSON.stringify()

Symbol-keyed properties will be completely ignored when using JSON.stringify() :

JSON.stringify({[Symbol('foo')]: 'foo'})
// '{}'
					

For more details, see JSON.stringify() .

Symbol wrapper objects as property keys

When a Symbol wrapper object is used as a property key, this object will be coerced to its wrapped symbol:

let sym = Symbol('foo')
let obj = {[sym]: 1}
obj[sym]             // 1
obj[Object(sym)]     // still 1
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol' in that specification.

浏览器兼容性

更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
Symbol Chrome 38 Edge 12
12
Edge 12 included Symbol properties in JSON.stringify() output.
Firefox 36 IE No Opera 25 Safari 9 WebView Android 38 Chrome Android 38 Firefox Android 36 Opera Android 25 Safari iOS 9 Samsung Internet Android 3.0 nodejs 0.12
Symbol() 构造函数 Chrome 38 Edge 12 Firefox 36 IE No Opera 25 Safari 9 WebView Android 38 Chrome Android 38 Firefox Android 36 Opera Android 25 Safari iOS 9 Samsung Internet Android 3.0 nodejs 0.12
asyncIterator Chrome 63 Edge 79 Firefox 57 IE No Opera 50 Safari 11.1 WebView Android 63 Chrome Android 63 Firefox Android No Opera Android 46 Safari iOS No Samsung Internet Android 8.0 nodejs 10.0.0
description Chrome 70 Edge 79 Firefox 63 IE No Opera 57 Safari 12.1
12.1
部分支持 12
No support for an undefined description.
WebView Android 70 Chrome Android 70 Firefox Android 63 Opera Android 49 Safari iOS 12.2
12.2
部分支持 12
No support for an undefined description.
Samsung Internet Android 10.0 nodejs 11.0.0
for Chrome 40 Edge 12 Firefox 36 IE No Opera 27 Safari 9 WebView Android 40 Chrome Android 40 Firefox Android 36 Opera Android 27 Safari iOS 9 Samsung Internet Android 4.0 nodejs 0.12
hasInstance Chrome 50 Edge 15 Firefox 50 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 50 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.5.0
6.5.0
6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.
isConcatSpreadable Chrome 48 Edge 15 Firefox 48 IE No Opera 35 Safari 10 WebView Android 48 Chrome Android 48 Firefox Android 48 Opera Android 35 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
iterator Chrome 43 Edge 12 Firefox 36 IE No Opera 30 Safari 10 WebView Android 43 Chrome Android 43 Firefox Android 36 Opera Android 30 Safari iOS 10 Samsung Internet Android 4.0 nodejs 0.12
keyFor Chrome 40 Edge 12 Firefox 36 IE No Opera 27 Safari 9 WebView Android 40 Chrome Android 40 Firefox Android 36 Opera Android 27 Safari iOS 9 Samsung Internet Android 4.0 nodejs 0.12
match Chrome 50 Edge 79 Firefox 40 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 40 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
matchAll Chrome 73 Edge 79 Firefox 67 IE No Opera 60 Safari No WebView Android 73 Chrome Android 73 Firefox Android 67 Opera Android 52 Safari iOS No Samsung Internet Android No nodejs 12.0.0
replace Chrome 50 Edge 79 Firefox 49 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 49 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
search Chrome 50 Edge 79 Firefox 49 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 49 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
species Chrome 51 Edge 13 Firefox 41 IE No Opera 38 Safari 10 WebView Android 51 Chrome Android 51 Firefox Android 41 Opera Android 41 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.5.0
6.5.0
6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.
split Chrome 50 Edge 79 Firefox 49 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 49 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
toPrimitive Chrome 47 Edge 15 Firefox 44 IE No Opera 34 Safari 10 WebView Android 47 Chrome Android 47 Firefox Android 44 Opera Android 34 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
toSource
非标
Chrome No Edge No Firefox 36 — 74
不支持 36 — 74
Starting in Firefox 74, toSource() is no longer available for use by web content. It is still allowed for internal and privileged code.
IE No Opera No Safari No WebView Android No Chrome Android No Firefox Android 36 Opera Android No Safari iOS No Samsung Internet Android No nodejs No
toString Chrome 38 Edge 12 Firefox 36 IE No Opera 25 Safari 9 WebView Android 38 Chrome Android 38 Firefox Android 36 Opera Android 25 Safari iOS 9 Samsung Internet Android 3.0 nodejs 0.12
toStringTag Chrome 49 Edge 15 Firefox 51 IE No Opera 36 Safari 10 WebView Android 49 Chrome Android 49 Firefox Android 51 Opera Android 36 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0
6.0.0
4.0.0
Disabled
Disabled From version 4.0.0: this feature is behind the --harmony runtime flag.
unscopables Chrome 45 Edge 12 Firefox 48 IE No Opera 32 Safari 9 WebView Android 45 Chrome Android 45 Firefox Android 48 Opera Android 32 Safari iOS 9 Samsung Internet Android 5.0 nodejs 0.12
valueOf Chrome 38 Edge 12 Firefox 36 IE No Opera 25 Safari 9 WebView Android 38 Chrome Android 38 Firefox Android 36 Opera Android 25 Safari iOS 9 Samsung Internet Android 3.0 nodejs 0.12
@@toPrimitive Chrome 47 Edge 15 Firefox 44 IE No Opera 34 Safari 10 WebView Android 47 Chrome Android 47 Firefox Android 44 Opera Android 34 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.0.0

图例

完整支持
完整支持
不支持
不支持
非标。预期跨浏览器支持较差。
非标。预期跨浏览器支持较差。
见实现注意事项。
用户必须明确启用此特征。
用户必须明确启用此特征。

另请参阅

Metadata