0

Basically, I want to build an object such that the following would be possible:

console.log(secretObject) // Outputs: 'A secret'
console.log(secretObject.secretKey) // Outputs: 523

So just like a normal object except when I call the object itself, instead of returning {secretKey: 523} it would return some other value.

Is this possible?

Edit: I am aware of toString(), but I want to know if there is a solution that would allow for any return value.

For some context, in my function I have many locations where I return false however I now realise that in only one of these cases I also need to return an additional value. Of course I can figure out a different way to do it, but I thought a relatively elegant solution would be to return an object that itself 'returned' false, but also could potentially contain other information inside.

So it's more out of curiosity than necessity, as to whether it is possible or not.

Keldan Chapman
  • 665
  • 5
  • 21
  • 1
    You can offer a `toString()` function in the object, which will be called implicitly when trying to stringify the object. Yet this will not change the output in the console, since it does not happen there. It would happen on `alert()` or `console.log(secretObject + '')`. However, it do not recoomend to change default behaviou of objects. – JavaScript Dec 09 '20 at 09:58
  • Yes I am aware of toString(). Maybe my example was bad. I would like it to work for any value. Strings, numbers, bools, other objects, etc. – Keldan Chapman Dec 09 '20 at 09:59
  • 1
    No, this is not possible. Atleast not as I think you wish to have it. The console, depending on the implementation of it, is always going to lookup the object keys and values. Even if you overwrite it in some cases, it is weird use-case and sounds like a bad idea. – JavaScript Dec 09 '20 at 10:03
  • instead of just returning false you could return an object where you set a property to check to false sth. like `{status:false,otherinfo:'123'}` you just have to check status then – john Smith Dec 09 '20 at 10:10
  • @johnSmith Yeah that will be my fallback, it just means that I'll need to rebuild my other code to behave with a returned object rather than a returned value. I just need to stop being lazy I guess – Keldan Chapman Dec 09 '20 at 10:17

0 Answers0