ES6 - Symbol.for()
此函数创建一个符号并添加到注册表中。如果符号已存在于注册表中,它将返回相同的符号;否则,将在全局符号注册表中创建一个新符号。
语法
Symbol.for(key)
其中,key是符号的标识符
示例
以下示例显示了Symbol()和Symbol.for()之间的区别>
<script>
const userId = Symbol.for('userId') // 在注册表中创建一个新的符号
const user_Id = Symbol.for('userId') // 重用已创建的符号
console.log(userId == user_Id)
const studentId = Symbol("studentID") // 创建符号但不在注册表中
const student_Id = Symbol.for("studentID")// 在注册表中创建一个新的符号
console.log(studentId == student_Id)
</script>
上述代码的输出将如下所示 −
true false

