How to Create & Use Classes in JavaScript ?
Last Updated :
06 Feb, 2024
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 Animal {
constructor(name, sound) {
this .name = name;
this .sound = sound;
}
makeSound() {
console.log(`${ this .name} says ${ this .sound}`);
}
}
const cat = new Animal( 'Cat' , 'Meow' );
const dog = new Animal( 'Dog' , 'Woof' );
cat.makeSound();
dog.makeSound();
|
Output
Cat says Meow
Dog says Woof
Share your thoughts in the comments
Please Login to comment...