JS Classes
A class is sugar on top of JavaScript's prototype chain. It packages data and methods together — useful when you have many instances that share behaviour.
Define and use
JS
class User {
// Fields and constructor
constructor(name, role = "member") {
this.name = name;
this.role = role;
}
// Methods
greet() {
return `Hi, ${this.name}!`;
}
// Static — called on the class, not an instance
static fromJSON(str) {
return new User(JSON.parse(str).name);
}
// Getter / setter
get isAdmin() { return this.role === "admin"; }
set role(r) { this._role = r.toLowerCase(); }
get role() { return this._role; }
}
const u = new User("Ada", "Admin");
u.greet(); // "Hi, Ada!"
u.isAdmin; // true
User.fromJSON('{"name":"Grace"}');
Inheritance with extends
JS
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound.`; }
}
class Dog extends Animal {
speak() {
return super.speak() + " Woof!";
}
}
new Dog("Rex").speak(); // "Rex makes a sound. Woof!"
Private fields
JS
class Counter {
#count = 0; // # marks it as private
increment() { this.#count++; }
get value() { return this.#count; }
}
const c = new Counter();
c.increment();
c.value; // 1
// c.#count; // ← syntax error from outside
Tip: Don't reach for classes by default — JavaScript also has plain objects and modules. Classes shine when you have many similar instances (UI components, records from a database) or want inheritance / polymorphism.
Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Classes!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Make Dog inherit from Animal.
class Dog
Animal { /* ... */ }
Seven letters.
Discussion
Loading…