JavaScript Classes
JavaScript classes are templates for creating objects that share the same structure and behavior. Under the hood they use prototypes, but the class syntax is cleaner and familiar from other languages.
Defining a Class
The constructor runs when you create an object with new. Methods are shared by all instances.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
label() {
return `${this.name}: ${this.price.toFixed(2)}`;
}
}
const p = new Product("Green Tea", 6);
console.log(p.label());Green Tea: $6.00
Private Fields, Getters and Setters
Fields starting with # are truly private: code outside the class cannot read them. Getters and setters look like properties but run code, which is useful for validation.
class Account {
#balance = 0;
get balance() {
return this.#balance;
}
deposit(amount) {
if (amount <= 0) throw new RangeError("Amount must be positive");
this.#balance += amount;
}
}
const acc = new Account();
acc.deposit(300);
console.log(acc.balance);
console.log(acc["#balance"]); // not accessible300 undefined
Static Members
Static methods belong to the class itself, not to instances. They are often used as factory functions or helpers.
class Temperature {
static fromFahrenheit(f) {
return new Temperature((f - 32) * 5 / 9);
}
constructor(celsius) {
this.celsius = celsius;
}
}
const t = Temperature.fromFahrenheit(212);
console.log(t.celsius);100
Inheritance with extends and super
A subclass inherits methods from its parent. Call super() in the constructor before using this, and super.method() to reuse the parent version.
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
speak() { return super.speak() + " - woof!"; }
}
const d = new Dog("Rex");
console.log(d.speak());
console.log(d instanceof Animal);Rex makes a sound - woof! true
When to Use Classes
Classes fit well when many objects share behavior and internal state, such as models, game entities or UI widgets. For simple data, plain objects and functions are often enough.
Frequently asked questions
Are JavaScript classes real classes?
They are syntax over prototype-based inheritance. The behavior is similar to classes in other languages, but methods live on the prototype object.
How do I make a private property in a JavaScript class?
Prefix it with #, for example #balance. It can only be accessed inside the class body.
Why must I call super() in a subclass constructor?
The parent constructor creates and initializes this. Using this before super() throws a ReferenceError.