JS Class

Sometimes, even synthetic suer is sweet

Class, needs no explanation. So let’s start simple:

class Me{
    name = "someone unknown";
    constructor(theName){
        this.name = theName;
    }
    
    sayHi(){
        return 'Hi';
    }
}

let me = new Me('I');
me.name;    // "I"
me.sayHi(); // 'Hi'

A class with a constructor that init the property “me”.

Now let’s add a private value with getter and a setter:

class Me{
    #name = "someone unknown";

    constructor(theName){
        this.#name = theName;
    }

    get name(){
        return `My name is ${this.#name}`;
    }

    set name(newName){
        this.#name = newName;
    }

    sayHi(){
        return 'Hi';
    }
}

let me = new Me('I');
me.name;  // "My name is I"
me.#name; // Uncaught SyntaxError: Private field '#name' must
             be declared in an enclosing class

By adding the # before the property value, it becomes private property.

Inheritance requires two additional changes:

class You extends Me{
    constructor(theName){
        super(theName);
    }

    get name(){
        return `Who cares about you?`;
    }
}

let you = new You('I');
you.name; // "Who cares about you?"

The same way, to access the parent method or property, use super:

class You extends Me{
    constructor(theName){
        super(theName);
    }
    set name(newName){
        super.name = newName;
    }

    get name(){
        return `Who cares about you?`;
    }

    sayHi(){
        return `${super.sayHi()} You`;
    }
}

Note that if you want to override a setter or getter, you need to override both.

Static methods or properties are part of the Class, but not of the instances. So the value is available only from the class itself. And as in the class, you can define private and public static properties and methods.

class Drink {
     static #NumnerOfDrings = 0;
     static MaxNumnerOfDrings = 3;
   
     static canDrink(){
        return Drink.#NumnerOfDrings < Drink.MaxNumnerOfDrings;
     }

    constructor(){
        if(Drink.canDrink()){
            ++Drink.#NumnerOfDrings;
        }else{
            throw "Nope, You can drink no more";
        }
    }

 }
 let drink1 = new Drink();
 let drink2 = new Drink();
 let drink3 = new Drink();
 let drink4 = new Drink();
     // Uncaught ReferenceError: Nope, you can drink no more!
     // drink4 is not defined     

Last issue is the “instance of”, but since time is up, I’ll write it in codeit 🙂

class A { constructor() {}}
class B extends A { constructor() {super();}}

a = new A();
b = new B();

 a instanceof A;     // true
 b instanceof B;     // true
 b instanceof A;     // true
 a.constructor == A; // true
 b.constructor == B; // true
 b.constructor == A; // false