2

What I want to achieve seems quite simple but I'm not sure if it's possible.

I'd like to have an object that returns a certain value if no property is specified. For example:

console.log(obj) // Returns "123" console.log(obj.x) // Returns "ABC" 
4
  • 1
    No, that's not possible. What would you need this for? Commented Mar 23, 2016 at 2:53
  • you can't do it for console.log(obj), but you can do it for console.log(obj + '') Commented Mar 23, 2016 at 2:54
  • 1
    Have a look over here though Commented Mar 23, 2016 at 2:55
  • @Bergi Misuse of that code will end in tears. I stand by your first answer. Commented Mar 23, 2016 at 2:59

2 Answers 2

1

Override the toString() method in the prototype for your custom object.

function MyObj() { } MyObj.prototype.toString = function () { return '123'; }; var obj = new MyObj(); obj.x = 'ABC'; console.log(obj + ''); console.log(obj.x + ''); 
Sign up to request clarification or add additional context in comments.

1 Comment

As @zb points out this only works by coercing the object into a string with + '' in the log call.
0

Here's how it can be done using Symbol's toPrimitive:

const primaryColor = { default: 'green', darker: 'silver', lighter: 'white', } Object.defineProperty(primaryColor, Symbol.toPrimitive, { value: () => primaryColor.default }); 

so, we got something like:

console.log('primary color: ' + primaryColor.darker) // returns "primary color: silver" console.log('primary color: ' + primaryColor) // returns "primary color: green" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.