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
语法
参数
返回值
描述
¥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.
示例
使用 Symbol.for()
¥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
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:
Symbol.for("mdn.foo");
Symbol.for("mdn.bar");
规范
Specification |
---|
ECMAScript Language Specification # sec-symbol.for |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also