简体   繁体   中英

Javascript Object with default value

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 + '');

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM