In this tutorial, we will learn about Class and Object usage in Javascript

Class :

  • A class is a blueprint for creating objects (instances), providing initial values for state (member variables or properties), and implementations of behavior (member functions or methods).
  • Classes define a constructor that is used to initialize the state of the object when it is created.
  • Classes also provide a way to encapsulate data and behavior into a single entity.

Object

  • An object, on the other hand, is an instance of a class and represents a specific entity
  • Objects have properties that store data, and methods that perform actions
  • Each object created from a class will have its own set of properties and methods, but they will all have the same structure as defined by the class.

JavaScript Class and Object Example:

// Define a class for a person
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.`);
  }
}

// Create an object from the Person class
let jayaram= new Person("Jayaram 30);

// Use the object's properties and methods
console.log(jayaram.name); // "John"
console.log(jayaram.age); // 30
john.sayHello(); // "Hello, my name is Jayaram and I am 30 years old."

In this example, a class Person is defined with a constructor that takes a name and an age as arguments. The class also has a method sayHello that prints a message to the console. An object john is then created from the Person class, and its properties and methods are used.

Thanks for Reading…

Comments are closed.