Class in JavaScript
In this tutorial, we will learn about classes in JavaScript.
Object-oriented programming(OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. One of the fundamental concepts of OOP is the class. In JavaScript, classes are used to define the blueprint for objects, allowing developers to create objects that share the same properties and methods.
Syntax
The syntax for creating a class in JavaScript is as follows:
class ClassName {
constructor() {
// Constructor
}
method1() {
// Method 1
}
method2() {
// Method 2
}
}In the above syntax:
ClassNameis the name of the class.constructoris a special method that is called when a new instance of the class is created.method1andmethod2are methods that define the behavior of the class.
Example
Let's create a simple class called Person that represents a person with a name and age:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person("John", 30);
person.greet();In the above example:
- We define a class called
Personwith a constructor that takesnameandageas parameters and assigns them to the object's properties. - We define a method called
greetthat logs a greeting message with the person's name and age. - We create a new instance of the
Personclass with the nameJohnand age30and call thegreetmethod.
JavaScript classes also support inheritance and polymorphism which are fundamental concepts of OOP. We will cover these concepts in detail in future tutorials.
Conclusion
- Classes in JavaScript are used to define the blueprint for objects.
- Classes have properties and methods that define the behavior of the objects.
- The
constructormethod is a special method that is called when a new instance of the class is created. - JavaScript classes support inheritance and polymorphism.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on