Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 class constructor shortcut for setting instance properties

I seem to remember seeing a shortcut where you didn't have to do this.foo assignments in the constructor if the property and the constructor argument was named the same thing - but I can't seem to find the reference for it googling around.

For example:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

Could you instead do something like

class Polygon {
  constructor(height=height, width=width) { 
     // wasn't there a way to declare these arguments so it auto sets the instance variables?
  }
}
like image 387
MonkeyBonkey Avatar asked Jan 05 '17 13:01

MonkeyBonkey


People also ask

How do I create an instance of a class in es6?

Creating Objects To create an instance of the class, use the new keyword followed by the class name. Following is the syntax for the same. Where, The new keyword is responsible for instantiation.

How do you instantiate a class in JavaScript?

The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.

How do you define a constructor in JavaScript?

A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.

What is the constructor in a class?

A constructor of a class is a special method that gets called when a class is instantiated using the NEW function. A constructor for a class has the same name as the class name. Unlike ordinary methods, a constructor definition is identified by the CONSTRUCTOR statement.


1 Answers

You could change it to:

class Polygon {
  constructor(height, width) {
    Object.assign(this, { height, width })
  }
}

This would mean you pass a singular object instead of multiple arguments

like image 173
Dan Gamble Avatar answered Sep 27 '22 20:09

Dan Gamble