Note Static members belong to the class itself, not instances. Access them via ClassName.method(), not instance.method().
static methodstatic propertyclass methodutility class
Inheritance (extends)
syntax
class Child extends Parent {
constructor(params) {
super(parentParams);
}
}
example
class Shape {
constructor(color) {
this.color = color;
}
describe() {
return`A ${this.color} shape`;
}
}
class Circle extends Shape {
constructor(color, radius) {
super(color);
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
describe() {
return`A ${this.color} circle (r=${this.radius})`;
}
}
const c = new Circle("blue", 5);
console.log(c.describe());
console.log(c.area.toFixed(2));
output
"A blue circle (r=5)"
"78.54"
Note super() must be called in the child constructor before accessing this. Methods can be overridden. Use super.method() to call the parent version.
class inheritanceextendssupersubclassoverride method
Private Fields and Methods
syntax
class C {
#privateField = value;#privateMethod() { ... }
}
example
class BankAccount {
#balance = 0;
constructor(initial) {
this.#balance = initial;
}
deposit(amount) {
this.#validateAmount(amount);this.#balance += amount;
}
get balance() {
returnthis.#balance;
}
#validateAmount(amount) {if (amount <= 0) thrownew Error("Amount must be positive");
}
}
const acct = new BankAccount(100);
acct.deposit(50);
console.log(acct.balance); // 150// acct.#balance; // SyntaxError
Note Private fields/methods use the # prefix. They are truly private -- not accessible outside the class, even by subclasses. instanceof checks still work.
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
const pet = new Dog();
console.log(pet instanceof Dog); // true
console.log(pet instanceof Animal); // true
console.log(pet instanceof Cat); // false
Note Checks the prototype chain. Can be unreliable across iframes or realms. For built-in types, prefer Array.isArray() over instanceof Array.
instanceoftype check classcheck class typeprototype chain
Mixins Pattern
syntax
const Mixin = (Base) => classextends Base { ... };
example
const Serializable = (Base) => classextends Base {
toJSON() {
return JSON.stringify({ ...this });
}
};
const Timestamped = (Base) => classextends Base {
constructor(...args) {
super(...args);
this.createdAt = new Date();
}
};
class User extends Timestamped(Serializable(Object)) {
constructor(name) {
super();
this.name = name;
}
}
const user = new User("Kai");
console.log(user.toJSON());
Note JavaScript has single inheritance only. Mixins simulate multiple inheritance by composing class factories. Order matters -- later mixins override earlier ones.