Search code examples
javascriptecmascript-6

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?
  }
}

Solution

  • If you're into this kind of things, you could probably define a super-class that does this:

    class BaseClass {
      constructor(names = [], values = []) {
        names.forEach((n, idx) => this[n] = values[idx]);
      }
    }
    
    class Polygon extends BaseClass {
      constructor(height, width) {
        super(['height', 'width'], arguments);
      }
    }
    

    Of course it's very debatable whether you should do this, but it's possible. Note that we could not rely on the names of the arg names in the constructor though because of possible minification problems.