ES6 class constructor shortcut for setting instance properties
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
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})
}
}
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}
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.