Level: Intermediate | Players: 12_Closure and_Scope
Learning Objectives
- Define an object blueprint using the
classgrammar. - Initialize the instance with
constructor. - Implement inheritance with
extendsandsuper. - Use
staticmethod and getter/setter. - We know that classes are prototype-based syntactic sugar.
1. Class basics
class Person {
constructor(name) {
this.name = name;
}
hello() {
return `Hi, I am ${this.name}`;
}
}
const p = new Person("Sun");
p.hello();
If called without new, it is a TypeError.
2. Inheritance (extends, super)
class Student extends Person {
constructor(name, grade) {
super(name);
this.grade = grade;
}
intro() {
return `${super.hello()} (grade ${this.grade})`;
}
}
super(...) calls the parent constructor, and super.method() calls the parent method.
3. static and getter/setter
Static members are attached to the class itself, not to the instance.
class MathX {
static square(x) { return x * x; }
}
MathX.square(5);
class Temp {
constructor(c) { this._c = c; }
get fahrenheit() { return this._c * 9/5 + 32; }
set fahrenheit(f) { this._c = (f - 32) * 5/9; }
}
4. Relationship with prototype
class uses function and prototype chains internally. This is Person.prototype.hello === p.hello.
Core example
| file | Contents covered |
|---|---|
01_class_basic.js |
class default |
02_constructor.js |
constructor and instance fields |
03_extends.js |
inheritance and super |
04_static_getter.js |
static, getter/setter |
⚠️ Common Mistakes
- Class call without
new→ TypeError. - Access
thisbeforesuper()in the child constructor. - When defining a method with an arrow function, a function is created for each instance, wasting memory.
- In the
staticmethod, there is a misunderstanding thatthispoints to an instance (points to a class). - You want to have properties with the same name as getter/setter at the same time.
❓ Frequently Asked Questions (FAQ)
Q1. What about private fields? A. You can create truly private fields with the #field syntax (ES2022+).
Q2. Multiple inheritance? A. Not supported. Utilizes the mixin pattern.
Q3. Class vs factory function? A. Class is newpart/inheritance stronger, and factory is easier to create private state with closure.