[Javascript] Symbol vs Symbol.for

Symbol.for("key")

Checks if a symbol with the key "key" already exists in the globals symbol registry.

If yes, it returns the existing symbol, otherwise, it creates a new symbol and adds it to the global regsitery.

 

Symbol("key")

Always creates a new, unique symbol that is different from any other symbol.

const one = Symbol.for("key")
const two = Symbol("key")
const three = Symbol.for("key")

console.log(one === two) // false
console.log(two === three) // false
console.log(one === three) // true
console.log(three === Symbol("key")) // false

 

posted @ 2024-03-22 02:39  Zhentiw  阅读(4)  评论(0编辑  收藏  举报