Search code examples
javascriptgetter-setter

Have object return primitive value instead of self on get


I know that the getter/setter methods of an object can be overwritten, but this requires specifying a property name. I'm looking for the following behaviour, which I could not find online:

let o = { a: '1', b: '2', (get: 'Hi!') };
console.log( o.a ) // 1
console.log( o.b ) // 2
console.log( o )   // 'Hi!'

Effectively have the object return something else when it is directly 'gotten'. I suppose another way to describe this is to have a default return value when a property is not accessed.


Solution

  • This is not currently possible.