In ECMAScript (ES) 6, a class is a blueprint or template for creating objects with similar properties and methods. Classes provide a way to encapsulate data and behavior in a single entity, making it easier to organize and reuse code.
Classes are often called syntactic sugar over JavaScript's existing prototype-based inheritance because they provide a more familiar syntax and structure for developers used to working with object-oriented programming languages like Java or C++. Inheritance is still achieved using the prototype chain, but classes provide a more organized way to define and use objects.
A class is defined using the class
keyword followed by the name of the class, a constructor function (if any), and an optional extends
clause that specifies the parent class (if any). Within the class definition, you can define methods (functions that operate on the data within an object) and properties (data members associated with an object).
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
}
makeSound() {
console.log(`${this.name} makes a sound!`);
}
}
const dog = new Animal('Fluffy', 'Dog');
dog.makeSound(); // Fluffy makes a sound!
In this example, the Animal
class defines a constructor function that initializes the name
and species
properties of the object created from the class. It also defines a makeSound()
method that operates on the data within an object (in this case, the name
property).
You can then create new objects from the class using the new
keyword, like in the example above where we create a new dog
object from the Animal
class.
class Dog extends Animal {
constructor(name, breed) {
super(name, 'Dog'); // call the parent constructor
this.breed = breed;
}
makeSound() {
console.log(`${this.name} barks!`);
}
}
const myDog = new Dog('Fluffy', 'Golden Retriever');
myDog.makeSound(); // Fluffy barks!
In this example, the Dog
class extends the Animal
class using the extends
keyword and calls the parent constructor using super()
. This allows us to inherit all the properties and methods of the Animal
class and add additional functionality specific to dogs. The makeSound()
method is also overridden to print "Fluffy barks!" instead of "Fluffy makes a sound!".