Symbol() constructor returns a value of type symbol , but is incomplete as a constructor because it does not support the syntax " new Symbol() " and it is not intended to be subclassed. It may be used as the value of an extends clause of a class definition but a super call to it will cause an exception.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

句法

Symbol([description])
					

参数

description 可选

A string. A description of the symbol which can be used for debugging but not to access the symbol itself.

范例

Creating symbols

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
					

new Symbol(...)

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');
let symObj = Object(sym);
typeof sym    // => "symbol"
typeof symObj // => "object"
					

规范

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

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 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 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

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: