此函数创建一个符号并添加到注册表中。如果该符号已经存在于注册表中,它将返回相同的;否则会在全局符号注册表中创建一个新符号。
用法
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 RegExp split()用法及代码示例
- ES6 Array every()用法及代码示例
- ES6 Array reduceRight()用法及代码示例
- ES6 handler.set()用法及代码示例
- ES6 handler.get()用法及代码示例
- ES6 Reflect.set()用法及代码示例
注:本文由纯净天空筛选整理自 ES6 - Symbol.for()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。