It's not as good as new syntax, but here's a getter / setter shorthand I've been playing around with once in a while. (I rarely use get / set to be honest.)
const A = ( x, y ) =>
Object.create( {}, {
x: { get: () => x, set: v => x = v },
y: { get: () => y, set: v => y = v },
sum: { get: () => x + y }
} );
const a = A( 5, 5 );
a.sum; //10
a.x = 10;
a.sum; //15
Of course, get / set are unnecessary for x and y above. Here's a cleaner form:
const A = ( x, y, self = { x, y } ) =>
Object.defineProperties( self, {
sum: { get: () => self.x + self.y }
} );
const a = A( 5, 5 );
a.sum; //10
a.x = 10;
a.sum; //15
What do you think? Other than the hideous "Object.defineProperties", it's actually shorter. You write the property name only once.
(You need self
, because as you noticed, arrow functions don't treat this
the way normal functions do.)
To get rid of the ugly "Object.X" part, you'll have to use a helper constructor like:
const Self = ( a, b ) =>
b ?
Object.defineProperties( a, b ) :
Object.create( {}, a );
And now we can have appropriately meaningful and beautiful syntax:
const A = ( x, y ) =>
Self( {
x: { get: () => x, set: v => x = v },
y: { get: () => y, set: v => y = v },
sum: { get: () => x + y }
} );
//Or:
const A = ( x, y, self = { x, y } ) =>
Self( self, {
sum: { get: () => self.x + self.y }
} );