ES6 - Symbol.for()



此函式建立一個符號並將其新增到登錄檔中。如果符號已存在於登錄檔中,則返回相同的符號;否則,將在全域性符號登錄檔中建立一個新的符號。

語法

Symbol.for(key) 

其中,key 是符號的識別符號

示例

以下示例顯示了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
廣告
© . All rights reserved.