JavaScript Classes
A class is a blueprint to create objects. It is the modern, cleaner way to write what constructor functions do.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return "Hi, I am " + this.name;
}
}
const p = new Person("Robin", 25);
console.log(p.greet());
console.log(p.age);
Output of the above program is
Hi, I am Robin
25
constructor()runs once when you usenew.- Methods are written without the
functionkeyword and go on the prototype automatically.
Getters and setters
class Circle {
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
}
const c = new Circle(2);
console.log(c.area.toFixed(2));
Output of the above program is
12.57
Static methods
class MathHelper {
static double(n) {
return n * 2;
}
}
console.log(MathHelper.double(5));
Output of the above program is
10
A static method belongs to the class itself, so you call it on the class, not on an object.
Inheritance with extends
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return this.name + " makes a sound";
}
}
class Dog extends Animal {
speak() {
return this.name + " barks";
}
}
const d = new Dog("Tommy");
console.log(d.speak());
console.log(d instanceof Animal);
Output of the above program is
Tommy barks
true
Use super to call the parent. In a child constructor you must call super() first.
class Puppy extends Dog {
constructor(name) {
super(name);
this.age = 1;
}
}
console.log(new Puppy("Bruno").age);
Output of the above program is
1
Private fields
class Account {
#balance = 0; // private
deposit(x) { this.#balance += x; }
get balance() { return this.#balance; }
}
const a = new Account();
a.deposit(100);
console.log(a.balance);
Output of the above program is
100
Note:
Under the hood, classes still use prototypes. A class is only a nicer way to write them.
Summary
classwith aconstructorand methods.extendsandsuperfor inheritance.staticfor class-level methods and#namefor private fields.- Next: JavaScript ES6 Features.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |