Horje
How to Create & Use Classes in JavaScript ?

In JavaScript, you can create and use classes to define blueprints for creating objects with similar properties and behaviors. Classes provide a way to implement object-oriented programming (OOP) concepts such as encapsulation, inheritance, and polymorphism.

Example: Here, we define a class called Animal, representing animals with a name and a sound. It has a method makeSound() to display the animal’s name and the sound it makes. Two instances of Animal class, cat and dog, are created with specific names and sounds ('Cat' and 'Meow' for cat, 'Dog' and 'Woof' for dog). Using these instances, the makeSound() method is called for each animal, displaying their names and respective sounds.

Javascript

// Class Declaration
class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }
 
  makeSound() {
    console.log(`${this.name} says ${this.sound}`);
  }
}
 
// Creating Instances
const cat = new Animal('Cat', 'Meow');
const dog = new Animal('Dog', 'Woof');
 
// Using Instances
cat.makeSound(); // Output: Cat says Meow
dog.makeSound(); // Output: Dog says Woof

Output

Cat says Meow
Dog says Woof




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Store an Object Inside an Array in JavaScript ? How to Store an Object Inside an Array in JavaScript ?
Alpine.js Alpine.js
How to Remove Duplicates from an Array of Objects using TypeScript ? How to Remove Duplicates from an Array of Objects using TypeScript ?
How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ? How to Add Duplicate Object Key with Different Value to Another Object in an Array in JavaScript ?
What is the use of Promises in JavaScript ? What is the use of Promises in JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12