1

I have a function ValidateInteger, that returns an object which looks something like:

{
    Value: "123",
    Neg: false,
    Exp: 3
}

I also have a class which calls this function:

class MyClass {
    constructor(val) {
        {
          Value: this.Value
          Neg: this.Neg
          Exp: this.Exp
        } = ValidateInteger(val);
    }
}

As you can see, there's quite a bit repetition with the this.

My question is there some better syntax to do this, something like:

this.{Value, Neg, Exp} = ValidateInteger(val);

There surely should be some better syntax for this.

mido
  • 24,198
  • 15
  • 92
  • 117
Downgoat
  • 13,771
  • 5
  • 46
  • 69

1 Answers1

5

I think you want Object.assign. It can be used to copy the values of enumerable properties from some objects to another one.

Object.assign(this, ValidateInteger(val));

var ValidateInteger = val => ({
  Value: "123",
  Neg: false,
  Exp: 3
});
class MyClass {
  constructor(val) {
    Object.assign(this, ValidateInteger(val));
  }
}
document.write('<pre>' + JSON.stringify(
  new MyClass() // MyClass { Value: "123", Neg: false, Exp: 3 }
, null, 2) + '</pre>');
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • The problem is that this will release *all* variables which I won't always want. [This](http://stackoverflow.com/a/31908049/1620622) answer is also recommending to avoid using Object.assign to release an object to a scope. – Downgoat Jan 11 '16 at 02:19
  • @Downgoat Bergi recommends not assigning random properties **to the global object**, and I completely agree. Here I am using `Object.assign` to assign properties to an instance. – Oriol Jan 11 '16 at 02:23
  • 1
    @Downgoat I don't know what you mean by "release all variables". It will assign all the properties in the object returned from `ValidateInteger` to `this`. This would be a problem only if the object returned from `ValidateInteger` included other properties which you do not want to assign to `this`; if that is the case, you will simply have to list them out. I also can't understand what you mean by "release an object to a scope". That answer is about something else entirely; it refers to defining **local variables** for all properties in an object. –  Jan 11 '16 at 03:51