Symbol.for(key) method searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. Otherwise a new symbol gets created in the global symbol registry with this key.

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.for(key);
					

参数

key

String, required. The key for the symbol (and also used for the description of the symbol).

返回值

An existing symbol with the given key if found; otherwise, a new symbol is created and returned.

描述

In contrast to Symbol() Symbol.for() function creates a symbol available in a global symbol registry list. Symbol.for() does also not necessarily create a new symbol on every call, but checks first if a symbol with the given key is already present in the registry. In that case, that symbol is returned. If no symbol with the given key is found, Symbol.for() will create a new global symbol.

Global symbol registry

The global symbol registry is a list with the following record structure and it is initialized empty:

A record in the global symbol registry
Field name Value
[[key]] A string key used to identify a symbol.
[[symbol]] A symbol that is stored globally.

范例

Using Symbol.for

Symbol.for('foo'); // create a new global symbol
Symbol.for('foo'); // retrieve the already created symbol
// Same global symbol, but not locally
Symbol.for('bar') === Symbol.for('bar'); // true
Symbol('bar') === Symbol('bar'); // false
// The key is also used as the description
var sym = Symbol.for('mario');
sym.toString(); // "Symbol(mario)"
					

To avoid name clashes with your global symbol keys and other (library code) global symbols, it might be a good idea to prefix your symbols:

Symbol.for('mdn.foo');
Symbol.for('mdn.bar');
					

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol.for' 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
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

图例

完整支持

完整支持

不支持

不支持

另请参阅

元数据

  • 最后修改: