🍄class
🚧 under construction
creates a new class and gives it a name (identifier).
no commas between class member declarations❗
private member identifiers are prefixed with hash (#).
// ⭐️ 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❗
⛔ cannot use a class before its declaration ❗(👉 temporal dead zone)
a class's prototype (property) is read-only❗
⭐️⭐️⭐️ you can change the prototype of a function, but not that of a class.
⛔ 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.
replit:TDZ: let/const/class
What class User {...} does:
creates a function User, function body taken from constructor().
stores methods in User.prototype.
⭐️ class is different from a regular function:
labelled by a special internal property
[[IsClassConstructor]].must be called with new.
methods are non-enumerable. (not enumerated in a for...in loop)
class body code always use strict.
⭐️ 注意:class 的語法與直接寫一個物件(literal object)的方式不同。
not block:
object literal / class / switch ( no block scope❗)
function's scope is different from a block scope❗
class identity
custom type name - define custom type name for class.
Complex - complex numbers.
other topics
custom functions
isClass() - check if value is a class.
JavaScript: The Definitive Guide ⟩ 5.7.3 class
MDN ⟩ JavaScript ⟩ Classes
Last updated
Was this helpful?