Caleb Mayhew Caleb Mayhew - 1 month ago 8
Javascript Question

Is there a way to make constructor assignments more concise (and simple)?

I was messing around with ES6 syntax today, and made up this basic test class:

class Animal {
constructor(type, age, name = "Unnamed Animal") {
this.type = type;
this.age = age;
this.name = name;
}
talkToMe() {
console.log(`Hi, my name is ${this.name}, and I am a ${this.type}!`);
}
}


Is there a way to make the constructor more concise using new ES6 syntax? Something, perhaps, like

constructor(type, age, name = "Unnamed Animal") {
this = {type, name, age};
}

Answer

I was going to say "no" because I was pretty certain that you have code as simple as it needs to be, but then I remembered Object.assign and the ability to use object constructor shorthand syntax.

If you've got a lot of properties to set, you can assign them all like this:

constructor(type, age, name = "Unnamed Animal") {
  Object.assign(this, {
    type,
    age,
    name
  });
}

This will come at a performance hit, and I think it's about equal as far as readability is concerned, but if typing this.prop = prop is annoying to you, this is an alternative.

Personally, I'd stick with:

this.name = name;
this.age = age;
this.type = type;
Comments