[ES2019] Represent Collision-free String Constants as Symbols in JavaScript

ES2019 introduces the Symbol.prototype.description property. In this lesson, we'll learn why this property is useful and unlocks Symbols as appropriate to use to represent strings constants in JS. We'll investigate a use case for string constants and see why using Symbols prior to ES2019 was not appropriate. Then we'll see how using .description fixes that. Lastly, we'll learn why using Symbols may be better than strings for constants in certain use cases by examining what it means to be "collision free".

If we define a Symbol:

const sy = Symbol('A')

Before ES2019, if we console.log `sy`, we will always get `Symbol(A)`.

After ES2019 we can get the value of Symbol:

console.log(sy.description) // 'A'

And Symbol are collision-free which means:

Symbol('a') === Symbol('a') //false
原文地址:https://www.cnblogs.com/Answer1215/p/11237854.html