当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


ES6 Symbol.for()用法及代码示例


此函数创建一个符号并添加到注册表中。如果该符号已经存在于注册表中,它将返回相同的;否则会在全局符号注册表中创建一个新符号。

用法

Symbol.for(key) 

其中,key是个identifier符号的

示例

以下示例显示了两者之间的区别Symbol()Symbol.for()

<script>
   const userId = Symbol.for('userId') // creates a new Symbol in registry
   const user_Id = Symbol.for('userId') // reuses already created Symbol
   console.log(userId == user_Id)    
   const studentId = Symbol("studentID") // creates symbol but not in registry
   const student_Id = Symbol.for("studentID")// creates a new Symbol in registry
   console.log(studentId == student_Id)
</script>

上面代码的输出将如下所示——

true
false

相关用法


注:本文由纯净天空筛选整理自 ES6 - Symbol.for()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。