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" 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 + ''); + '' in the log call.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"
console.log(obj), but you can do it forconsole.log(obj + '')