點燈坊

失くすものさえない今が強くなるチャンスよ

Using Symbol Property to Make Property Invisible

Sam Xiao's Avatar 2021-12-05

If we want to add invisible properties to the Object, we can use Symbol Property to make properties invisible.

Version

ECMAScript 2015

Symbol Property

let age = Symbol ('age')

let obj = {
  name: 'Sam',
  [age]: 18
}

Object.keys (obj) // ?
Object.getOwnPropertyNames (obj) // ?
JSON.stringify (obj) // ?

for (let x in obj)
  console.log (x)

Line 1

let age = Symbol ('age')

Use Symbol as property name.

Line 3

let obj = {
  name: 'Sam',
  [age]: 18
}

Use [] with Symbol to define a property.

Line 8

Object.keys (obj) // ?
Object.getOwnPropertyNames (obj) // ?
JSON.stringify (obj) // ?

for (let x in obj)
  console.log (x)

Object.keys, Object.getOwnPropertyNames, JSON.stringify and for of loop will not show property names defined by Symbol. It looks like an invisible property.

invisible000

Display Symbol Property

let age = Symbol ('age')

let obj = {
  name: 'Sam',
  [age]: 18
}

Object.getOwnPropertySymbols (obj) // ?
Reflect.ownKeys (obj) // ?
obj [age] // ?
  • Object.getOwnPropertySymbols : display all Symbol Properties
  • Reflect.ownKeys : display all properties including Symbol Properties
  • Use [] to display Symbol Property

invisible001

Conclusion

  • Symbol Property is a new property for Object. It is invisible by the traditional method; we have to use particular APIs to make it visible