JS Classes
On this page
JS Classes
JavaScript classes provide a cleaner syntax for working with objects and prototypes. They are syntactic sugar over prototype-based inheritance.
class User {
constructor(name) {
this.name = name;
}
greet() {
return "Hello, " + this.name;
}
}
const u = new User("Ozan");
console.log(u.greet());
Classes are not hoisted like function declarations.
JS Class Inheritance
Classes can inherit from other classes using extends. Use super() to call the parent constructor.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return "Some sound";
}
}
class Dog extends Animal {
speak() {
return "Woof";
}
}
const d = new Dog("Max");
console.log(d.name);
console.log(d.speak());
Always call super() in the child constructor before using this.
JS Class Static
Static methods belong to the class itself, not to instances.
class MathHelper {
static square(n) {
return n * n;
}
}
console.log(MathHelper.square(5));
// const m = new MathHelper();
// m.square(5); // Error
Modern features inside classes:
- Private fields:
#secret - Public class fields
class Counter {
#count = 0;
inc() {
this.#count++;
return this.#count;
}
}
const c = new Counter();
console.log(c.inc());
Next Step
Continue with JS Asynchronous to understand Promises, async/await, and Fetch.