Anton Eriksson
Anton Eriksson

Reputation: 169

How to set multiple class properties to properties of one object

The problem I'm facing is that I don't want have to call a function which returns both properties twice, instead I basically want to do this:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       { this.x, this.y } = foo(arg); //this function returns an object with two properties
   }

}

Instead of this:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       this.x = foo(arg).x;
       this.y = foo(arg).y;
   }
}

Upvotes: 1

Views: 1967

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075755

As already noted, you could use Object.assign, but beware that it assigns all of the (own, enumerable) properties in the object returned by foo.

To avoid that, you can use destructuring:

const {x, y} = foo(arg);
this.x = x;
this.y = y;

It doesn't gain you much, but...

You can combine the approaches:

const {x, y} = foo(arg);
Object.assign(this, {x, y});

...at the cost of (in theory) a temporary object allocation. (I say "in theory" since the JavaScript engine can optimize it out. But I don't know that it would.)


It's for situations like this that this proposal was put forward. Sadly, it hasn't gotten any traction to speak of with the committee. If that proposal were to go forward, you'd be able to do this:

// NOT STANDARD JAVASCRIPT (the proposal hasn't even been accepted for Stage 0)
this.{x, y} = foo(arg);

Upvotes: 1

wilsonzlin
wilsonzlin

Reputation: 2230

Assuming foo(arg) returns an object with only x and y properties:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       Object.assign(this, foo(arg));
   }
}

If foo might return more properties, you'll need to manually grab the properties:

class xy {
   x: number;
   y: number;

   constructor (arg) {
       const {x, y} = foo(arg);
       Object.assign(this, {x, y});
   }
}

Upvotes: 2

Related Questions