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