ES6 class constructor shortcut for setting instance properties

javascript class constructor
javascript class instance variables
javascript constructor
es6 class extends
typescript class constructor shorthand
es6 class best practices
ecmascript 6 classes
nodejs class

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

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.

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  The Example given above declares a class ‘Polygon’. The class’s constructor takes two arguments - height and width respectively. The ‘this’ keyword refers to the current instance of the class. In other words, the constructor above initializes two variables h and w with the parameter values passed to the constructor.

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

constructor, An instance has exactly the same properties of its parent class (no more, no less). Instead, you define a constructor function to create objects with a particular JavaScript provides a shortcut: the instanceof operator tests an  With that background out of the way, it’s time to examine ES6 class syntax. The previous code sample translates directly to the new syntax as follows: As before, each class consists of a constructor function and a prototype object which refer to each other via the prototype and constructor properties.

extend the prototype for more consice constructors

Object.prototype.initialize = function (obj) { Object.assign(this,obj) }

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

Details of the object model, One of the characteristics of this proposal is that subclass constructors must explicitly class Base2 { constructor(x) { this = [ ]; //create a new exotic array instance Object. If a derieved class does not explicitly define a constructor method it  A class constructor (the pseudo-method constructor in a class literal) uses it like a function call (super(···)), in order to make a super-constructor call (line A). Method definitions (in object literals or classes, with or without static ) use it like property references ( super.prop ) or method calls ( super.method(···) ), in order to refer to super-properties (line B).

You are probably remembering ES6 object literal shorthand syntax:

function makePolygon(height,width){
    return {height,width}; // in ES5 was return {height:height,width:width};
}

let poly = makePolygon(10,10);
console.log(poly); // {height: 10, width: 10}

Another way to solve your problem is to use an ES6 class with a configuration object and default parameters:

class Polygon{
    constructor(config={}){
        this.name = "Triangle";
        this.height = 10;
        this.width = 10;
        this.numSides = 3;
        Object.assign(this,config);
    }
}

let triangle = new Polygon();
let square = new Polygon({name: "Square", numSides: 4});
let pentagon = new Polygon({name: "Pentagon", numSides:5,height: 20,width: 20});

console.log(triangle,square,pentagon);
// Polygon {name: "Triangle", height: 10, width: 10, numSides: 3}
// Polygon {name: "Square", height: 10, width: 10, numSides: 4}
// Polygon {name: "Pentagon", height: 20, width: 20, numSides: 5}

New ES6 constructor features and semantics: Alternative 2 manual , Each object is just a mapping of strings and symbols to property descriptors. except that there is no distinction between type objects and instance objects With an old style class, you define the constructor function, and the  Class expressions. A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body. (it can be retrieved through the class's (not an instance's) name property, though).

How about using destruction:

class Polygon {
  constructor({height, width}) { Object.assign(this, arguments[0]); }
}

Though, creating this object will require creating a "config" object which, depending on your view, either adding clutter to the code or making it more readable:

console.log(new Polygon({height: 100, width: 200}));

will print:

Polygon {height: 100, width: 200}

One nice thing about this method is that if you receive polygon objects from the server as json, it is now trivially to revive them to their corresponding class:

let dataFromServer = "{\"polygons\":[{\"height\":10,\"width\":20},{\"height\":30,\"width\":40}]}";

console.log(JSON.parse(dataFromServer, (key, value) => {
  if (key === "polygons") return value.map(it => new Polygon(it));
  return value;
}));

How ES6 classes really work and how to build your own, You use this class just like an ES5 constructor function: A class body can only contain methods, but not data properties. Prototypes having data You can define the name of a method via an expression, if you put it in square brackets. The instance object is created in different locations in ES6 and ES5:. The constructor method is a special method for creating and initializing an object created within a class. class Polygon { constructor () { this.name = "Polygon"; } } var poly1 = new Polygon (); console.log (poly1.name); // expected output: "Polygon" The source for this interactive example is stored in a GitHub repository.

Classes in ECMAScript 6 (final semantics), const greeting = `Good morning!`; const shortcut = ``cmd` + `shift` + `G``; Prior to ES6, there was basically no syntax for setting default values for function the class constructor logic and also set all the instance properties. The constructor() method is a special method called when an instance of the User class is created. This is essentially the same as the User function we defined in the pre-ES6 example. Methods

JavaScript ES6: 5 new abstractions to improve your code , JavaScript classes initialize instances with constructors, have fields and methods, permit every object inherits properties and methods from its prototype object. User 's constructor has one parameter name , which is used to set the initial inside of a child method, you can use the special shortcut super . We describe the properties we want on our class instance. Each class has a special constructor function, this is called when we create an instance of a class with new. We describe the functions, also known as methods, that we want on our class instance. this in a method points to the class instance, the object that is created using this class.

The Complete Guide to JavaScript Classes, The cheatsheet contains references to types, classes, decorators, and many other Omit type when extending an interface; Omitting specific properties when Setting up Event Handlers; TypeScript and React Hooks Meaning, it can execute the constructor, then save the instance as a member of the same class. It is also  Whenever a class or struct is created, its constructor is called. A class or struct may have multiple constructors that take different arguments. Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read. For more information and examples, see Using Constructors and Instance

Comments
  • You're probably thinking of something like this in Typescript: typescriptlang.org/docs/handbook/…
  • ah yes that was it - so it's a typescript only technique and not es6?
  • I don't remember anything like that being in ES itself.
  • ok - yeah then it's the typescript feature I'm thinking about. Go ahead and create the answer and I'll accept it.