JavaScriptLesson 13 of 16

Classes

A class is a blueprint: with new you build as many similar objects from it as you like. Every account has its own owner and balance, while the rules for deposits and withdrawals are shared.

Key points

  • class Name { constructor(…) { this.x = … } } is the blueprint with starting properties
  • new Name(…) creates an object, and every such object gets the class methods
  • get balance() { … } is a getter: you read it like a property, without brackets
  • #balance is a private field: code outside the class can neither read nor change it
  • class B extends A inherits; super(…) calls the parent constructor

Example

class Point {  constructor(x, y) {    this.x = x;    this.y = y;  }   move(dx, dy) {    this.x += dx;    this.y += dy;  }   toString() {    return `(${this.x}, ${this.y})`;  }} class Point3D extends Point {  constructor(x, y, z) {    super(x, y);    this.z = z;  }   toString() {    return `(${this.x}, ${this.y}, ${this.z})`;  }} const p = new Point(1, 2);p.move(3, 4);console.log(`${p}`);console.log(`${new Point3D(1, 2, 3)}`);

Point3D inherited move from Point and replaced toString. super(x, y) handed x and y to the Point constructor. Inside a template literal an object becomes text through its toString.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Finish the tiny bank: deposit adds to #balance, withdraw takes money out or prints Not enough money when there is not enough. In SavingsAccount, add addInterest(percent), which deposits percent per cent of the balance. Output: Not enough money, Nora: 165 and true.

Output

What your program prints appears here.