Tsallaka zuwa abun ciki
Justice Tech School

Classes

A class describes what its objects have and can do. The constructor sets up each new object, methods are shared, and new creates an instance. Use # before a name for a private field.

Example
class Student {
  #score = 0;
  constructor(name) {
    this.name = name;
  }
  addScore(points) {
    this.#score += points;
    return this;
  }
  get total() {
    return this.#score;
  }
  describe() {
    return this.name + " has " + this.#score + " points";
  }
}
const ada = new Student("Ada");
ada.addScore(10).addScore(5);
console.log(ada.describe());
console.log(ada.total);

Exercise

Create an instance.

const s =  Student("Ada");

Quiz Test

What does the constructor do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.