此函數創建一個符號並添加到注冊表中。如果該符號已經存在於注冊表中,它將返回相同的;否則會在全局符號注冊表中創建一個新符號。
用法
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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。