Classes and Methods
Constructor Initialization
Initialize instance fields in a constructor.
Constructor Initialization
constructor_init.js
const width = 4;
class Box {
constructor(width, height) {
this.area = width * height;
}
getArea() {
return this.area;
}
}
const area = new Box(width, 3).getArea();
console.log("width=" + width);
console.log("area=" + area);
constructor-init
The constructor runs when an instance is created. Use it to compute and store the fields that later methods need.