點燈坊

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

Using Symbol Method to Make Method Invisible

Sam Xiao's Avatar 2021-12-05

If we want to add invisible methods to the Object, we can use Symbol Method to make methods invisible.

Version

ECMAScript 2015

Normal Method

let obj = {
  name: 'Sam',
  age: 18,
  toString: function () {
    return `${this.name} is ${this.age}`
  }
}

Object.keys (obj) // ?
Object.getOwnPropertyNames (obj) // ?
JSON.stringify (obj) // ?
for (let x in obj)
  console.log (x)

obj.toString () // ?

obj is an Object with toString method, if we use Object.keys, Object.getPropertyNames, JSON.stringify or for in loop, we’ll also get toString property.

If we want obj to be a pure Object, we may not want to see method names as properties. That is, we want toString to be invisible methods.

invisible000

Invisible Method

let toString = Symbol ()

let obj = {
  name: 'Sam',
  age: 18,
  [toString]: function () {
    return `${this.name} is ${this.age}`
  }
}

Object.keys (obj) // ?
Object.getOwnPropertyNames (obj) // ?
JSON.stringify (obj) // ?
for (let x in obj)
  console.log (x)

obj [toString] () // ?

Line 1

let toString = Symbol ()

Use Symbol as method name.

Line 6

[toString]: function () {
  return `${this.name} is ${this.age}`
}

Use [] with Symbol to define a method.

Line 11

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 method names defined by Symbol. It looks like an invisible method.

Line 17

obj [toString] () // ?

We have to use [] to execute this invisible method.

invisible000

Conclusion

  • Since Symbol Method is invisible by JSON.stringify, we can use JSON.strigify to serialize the Object to String and save it to the database