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.
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 PropertiesReflect.ownKeys
: display all properties including Symbol Properties- Use
[]
to display Symbol Property
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