Symbol.for()

Symbol.for() 静态方法使用给定键在运行时范围的符号注册表中搜索现有符号,如果找到则返回。否则,将使用此键在全局符号注册表中创建一个新符号。

¥The Symbol.for() static 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.

Try it

语法

¥Syntax

js
Symbol.for(key)

参数

¥Parameters

key

字符串,必填。符号的键(也用于符号的描述)。

返回值

¥Return value

具有给定键的现有符号(如果找到);否则,将创建并返回一个新符号。

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

描述

¥Description

Symbol() 相比,Symbol.for() 函数创建 全局符号注册表 列表中可用的符号。Symbol.for() 也不一定在每次调用时创建一个新符号,但首先检查具有给定 key 的符号是否已存在于注册表中。在这种情况下,将返回该符号。如果没有找到具有给定键的符号,Symbol.for() 将创建一个新的全局符号。

¥In contrast to Symbol(), the 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.

示例

¥Examples

使用 Symbol.for()

¥Using Symbol.for()

js
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
const 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:

js
Symbol.for("mdn.foo");
Symbol.for("mdn.bar");

规范

Specification
ECMAScript Language Specification
# sec-symbol.for

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also