Learn object-oriented programming with JavaScript classes and inheritance patterns.
Here’s an example demonstrating class creation and inheritance:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.
This code demonstrates:
Animal
.Dog
.super
to refer to the parent class constructor or methods.JavaScript classes are templates for creating objects. They encapsulate data with code to work on that data.
class
keyword. Contains a constructor and methods.extends
keyword to create a subclass.This approach simplifies the use of object-oriented programming in JavaScript by abstracting prototype chains and improving code readability and reusability.
Q1: What does the extends
keyword do in JavaScript?
Answer: C. Allows a class to inherit from another class
Q2: How do you call the parent class’s constructor from a subclass?
Answer: B. super()
Q3: Which of the following statements about JavaScript classes is true?
Answer: B. They are purely syntactic sugar over prototypes.
Q4: Which method is automatically called when an object is created from a class?
Answer: C. constructor()