Understanding Classes in JavaScript

Understanding Classes in JavaScript

Understanding Classes in JavaScript

Classes are an important feature of Object-Oriented Programming (OOP) in JavaScript. They allow you to create objects that have similar properties and methods, without having to create each object individually. In this tutorial, we will explore how to define and use classes in JavaScript.

Defining Classes in JavaScript

Defining a class in JavaScript involves using the "class" keyword, followed by the name of the class. Here is an example:


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.");
  }
}
    

In this example, we have defined a class called "Person". The class has a constructor function that takes two parameters, "name" and "age", and assigns them to the respective properties of the object. The class also has a method called "sayHello" that logs a message to the console.

Creating Objects from Classes

To create an object from a class, we use the "new" keyword followed by the name of the class, and any necessary arguments for the constructor function. Here is an example:


let person1 = new Person("John", 30);
let person2 = new Person("Jane", 25);

person1.sayHello();
person2.sayHello();
    

In this example, we have created two objects, "person1" and "person2", from the "Person" class. We have passed in the necessary arguments for the constructor function, and then called the "sayHello" method on each object.

Inheritance

Inheritance is another important concept in OOP. It allows you to create a new class based on an existing class, and then add or override properties and methods as needed. In JavaScript, we can achieve inheritance using the "extends" keyword. Here is an example:


class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  sayHello() {
    console.log("Hello, my name is " + this.name + " and I am " + this.age + " years old. I am in grade " + this.grade + ".");
  }
}
    

In this example, we have created a new class called "Student" that extends the "Person" class. The "Student" class has a constructor function that takes three parameters, including "name" and "age" from the "Person" class, and a new property "grade". The "Student" class also has a method called "sayHello" that overrides the "sayHello" method from the "Person" class to include the "grade" property in the console message.

Conclusion

Classes are a powerful feature

Комментарии

Популярные сообщения из этого блога

How To Modify CSS Classes in JavaScript

How To Backup MySQL Databases on an Ubuntu VPS

How To Backup PostgreSQL Databases on an Ubuntu VPS