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?
}
}
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.
The new operator instantiates the class in JavaScript: instance = new Class() . const myUser = new User(); new User() creates an instance of the User class.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With