🍄class

🚧 under construction

JSvalueobject ⟩ class

(declaration) ⭐️ ES6 (2015)

creates a new class and gives it a name (identifier).

// ⭐️ class definition
class A { 

    // ⭐️ instance members  (# means "private")
    publicProp;                     // this.publicProp = undefined (by default)
    publicMethod() { ... }          // this.publicMethod()
    
    #privateProp;                   // this.#privateProp
    #privateProp2 = 0;
    
    get #privateGetter() { ... }    // this.#privateGetter
    #privateMethod() { ... }        // this.#privateMethod()
    
    // ⭐️ static members
    static staticProp;              // A.staticProp
    
    // ⭐️ if omitted, a default (empty) constructor is created automatically.
    constructor() { ... }
}

// ⭐️ class expression
let B = class { ... }

class declaration is not hoisted

a class's prototype (property) is read-only

⭐️⭐️⭐️ you can change the prototype of a function, but not that of a class.

// overwrite a function's prototype is OK
func.prototype = {}     // ✅ OK

// overwrite a class's prototype won't work
Class.prototype = {}    // ❌ won't work (ignored silently❗️)

ReferenceError: cannot access '...' before initialization.

an error mostly caused by referencing a let/ const/ class in its temporal dead zone

using typeof on lexical declaration (let/ const/ class) in its temporal dead zone will throw a ReferenceError.

// ⭐ temporal dead zone (start)
// ------------------------------
// typeof aLet;       // ⛔ ReferenceError: Cannot access 'aLet' before initialization
// typeof aConst;     // ⛔ ReferenceError: Cannot access 'aConst' before initialization
// typeof aClass;     // ⛔ ReferenceError: Cannot access 'aClass' before initialization

typeof undeclared;        // ❗ 'undefined'

// ⭐ lexical declarations (let/const/class)
// --------------------------------------------
let aLet;                 // ⭐ initialized to `undefined`
const aConst = "hello";
class aClass {}

Last updated