I can specify linearized values for anonymous objects like this:
const foo = {
a: 123,
b: "xyz",
valueOf() {return this.a;},
toString() {return this.b;}
}
console.log(+foo); // 123
console.log(`${foo}`); // xyz
or with arrow functions:
const foo = {
a: 123,
b: "xyz",
valueOf: () => this.a,
toString: () => this.b
}
console.log(+foo); // 123
console.log(`${foo}`); // xyz
I wish there was a concise way to do this without having to explicitly name valueOf
and toString
. IΚΌm not sure how that would look though.
const foo = {
a: 123,
b: "xyz"
} => [+a, `$b`];
const foo = {
a: 123,
b: "xyz"
} => a; // only valueOf()
const foo = {
a: 123,
b: "xyz"
} => b; // only toString()
const foo = {
a: 123,
b: "xyz"
} => {
valueOf: a,
toString: b
}
bergus
March 9, 2020, 7:15pm
2
I don't see what's wrong with using method syntax for methods? (Notice the arrow function example doesn't actually work).
Why are you defining object literals with valueOf
/toString
methods often enough that you wish there was a special syntax for it? I can't see that happen in regular code - if you have that many object literals, use a factory function or even class
for it.
And even if they're all different, you can factor out the shared parts into a helper function, like
function withToPrimitive(obj, valueProp, stringProp) {
if (valueProp) obj.valueOf = () => obj[valueProp];
if (stringProp) obj.toString = () => obj[stringProp];
return obj;
}
const foo = withToPrimitive({
a: 123,
b: "xyz",
}, "a", "b");
2 Likes
awbjs
March 15, 2020, 12:47am
3
const abobj =
valueOf() {return this.a;},
toString() {return this.b;}
}
const foo = {
__proto__ : abobj,
a: 123,
b: "xyz",
}
const var = {
__proto__ : abobj,
a: 456,
b: "abc",
}
etc.
ItΚΌs mostly sugar for quick and dirty code.
At least for simple cases, I could also envision markers like so:
const foo = {
a: 123 __value,
b: "xyz" __string,
}
bergus
March 16, 2020, 9:49am
5
Adding new syntax to ECMAScript has a high cost, I doubt they'll add more syntactic sugar that's only useful in quick'n'dirty code.