Can I use Object.assign to assign properties to this in Javascript?

Asked

Viewed 77 times

4

I’m learning about objects now and I’d like to know if it’s possible to use Object.assign to assign all properties to this of a class in Javascript.

Example:

class Foo {
  name;
  email;
  phone;

  constructor(name, email, phone) {
    this.name = name;
    this.email = email;
    this.phone = phone;
  }

  method() {
    console.log(this.name, this.email, this.phone);
  }
}

Transform the code snippet above to the solution below:

class Foo {
  name;
  email;
  phone;

  constructor(name, email, phone) {
    Object.assign(this, name, email, phone);
  }

  method() {
    console.log(this.name, this.email, this.phone);
  }
}

1 answer

2


Yes. As I explained in this answer, the Object.assign uses internal operation [[Set]] to set the properties of objects passed from the second argument onwards to the object passed as the first argument. Thus, it is the same thing to assign properties explicitly using the assignment operator (=), which also uses the operation [[Set]].

However, note that you are not passing objects from the second argument on, but rather primitive values (probably strings):

Object.assign(this, name, email, phone);
//                  ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
//                  Devem ser objetos.

Note that name, email and phone are (probably) strings, not objects. Therefore, you should use:

//                  ↓                    ↓
Object.assign(this, { name, email, phone });

Note that above was used the abbreviated notation of property names to create the literal object. It was introduced in Ecmascript 2015 (ES6).

Example:

class Foo {
  constructor(name, email, phone) {
    Object.assign(this, { name, email, phone });
  }

  method() {
    console.log(this.name, this.email, this.phone);
  }
}

const inst = new Foo('a', 'b', 'c');
inst.method(); // a b c


Note that I added a semicolon to the code. It may sound "fresh" and I know that Javascript "accepts" the semicolon and "works" code, but it avoids some bizarre situations that can occur if you don’t use them, like this and this (see more about this here).

I also removed the property initializers at the beginning of the class since they were doing nothing there, since the properties will already be initialized in the constructor.

  • 1

    Wow, a real class!!! Man, thank you so much for the explanation, I searched other sites, articles and even videos and did not find anything as objective and as didactic as your reply!! thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.