In this JavaScript lesson we are going to talk about JavaScript Classes. so in ES6 the keyword class was introduced, a class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class.
In the past we can do like this.
1 2 3 4 5 6 7 8 |
function Display(name) { this.name = name; } myname = new Display("Parwiz"); console.log(myname); |
Now let’s convert our example with ES6 classes.
1 2 3 4 5 6 7 8 9 |
class Display { constructor(name) { this.name = name; } } let myname = new Display("John Doe") console.log(myname); |
Let’s add functions in our class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Display { constructor(name) { this.name = name; } greeting() { console.log("Hello From Method Class") } } let myname = new Display("John Doe") console.log(myname); myname.greeting() |
JavaScript Classes Features
As we already mentioned that Classes are feature in JavaScript that provide a way to define and create objects using a class based syntax. these are some features of JavaScript classes along with code examples:
- Class Declaration: You can define a class using the class keyword followed by the class name.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Person { constructor(name, age) { this.name = name; this.age = age; } sayHello() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } const person = new Person("John", 30); person.sayHello(); // "Hello, my name is John and I am 30 years old." |
In this example, the Person class is defined with constructor and sayHello method. An instance of the Person class is created and the sayHello method is called.
- Inheritance: You can create subclass that inherits from a parent class using the extends keyword.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Animal { constructor(name) { this.name = name; } speak() { console.log(`${this.name} makes a noise.`); } } class Dog extends Animal { speak() { console.log(`${this.name} barks.`); } } const dog = new Dog("Rufus"); dog.speak(); // "Rufus barks." |
In this example Animal class is defined with constructor and speak method. Dog class is defined as subclass of Animal and overrides the speak method to make the dog bark.
- Static Methods: You can define static methods on class using the static keyword. Static methods can be called on the class itself rather than on an instance of the class.
1 2 3 4 5 6 7 8 9 10 11 12 |
class MathUtils { static square(x) { return x * x; } static cube(x) { return x * x * x; } } console.log(MathUtils.square(5)); // 25 console.log(MathUtils.cube(5)); // 125 |
In this example, the MathUtils class is defined with static methods square and cube. static methods can be called on the class itself to perform mathematical operations.
In conclusion we can say that classes in JavaScript provide powerful and flexible way to create objects and perform object oriented programming. They are easy to read and can help make your code more organized and maintainable.