Initialize instance fields in a constructor.

constructor-init The constructor runs when an instance is created. Use it to compute and store the fields that later methods need.

Constructor Initialization

width
constructor_init.js
Replay: real traced execution (multi-file project)
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);
const width = 6;
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);
const width = 9;
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);
  1. width ← 4, this.area ← 12

    1const width→ 4 = 4; //@width=6, 92class Box {3  constructor(width, height) {4    this.area = width→ 4 * height3;5  }67  getArea() {8    return this.area;9  }10}1112const area = new Box(width4, 3).getArea();
    values this step12this.area
  2. getArea()

    4  this.area = width * height;5}67getArea() {8  return this.area12;9}
  3. area ← 12

    9  }10}1112const area→ 12 = new Box(width4, 3).getArea();1314console.log("width=" + width4);15console.log("area=" + area12);
    outputwidth=4
    area=12
  1. width ← 6, this.area ← 18

    1const width→ 6 = 6;2class Box {3  constructor(width, height) {4    this.area = width→ 6 * height3;5  }67  getArea() {8    return this.area;9  }10}1112const area = new Box(width6, 3).getArea();
    values this step18this.area
  2. getArea()

    4  this.area = width * height;5}67getArea() {8  return this.area18;9}
  3. area ← 18

    9  }10}1112const area→ 18 = new Box(width6, 3).getArea();1314console.log("width=" + width6);15console.log("area=" + area18);
    outputwidth=6
    area=18
  1. width ← 9, this.area ← 27

    1const width→ 9 = 9;2class Box {3  constructor(width, height) {4    this.area = width→ 9 * height3;5  }67  getArea() {8    return this.area;9  }10}1112const area = new Box(width9, 3).getArea();
    values this step27this.area
  2. getArea()

    4  this.area = width * height;5}67getArea() {8  return this.area27;9}
  3. area ← 27

    9  }10}1112const area→ 27 = new Box(width9, 3).getArea();1314console.log("width=" + width9);15console.log("area=" + area27);
    outputwidth=9
    area=27