Prepare for the Salesforce JavaScript Developer Exam. Utilize comprehensive quizzes, flashcards, and multiple choice questions with hints and explanations. Boost your exam readiness!

Practice this question and more.


Which constructor is correct for successfully extending the Dog class? class Dog { constructor(name) { this.name = name; } }; class Labrador extends Dog { // ... }

  1. constructor(name, size) { this.size = size; }

  2. constructor(name, size) { super(name); this.size = size; }

  3. constructor(size) { super(name); this.size = size; }

  4. constructor(name, size) { this.name = name; this.size = size; }

The correct answer is: constructor(name, size) { super(name); this.size = size; }

The choice provides a correct implementation of a constructor for the Labrador class that effectively extends the Dog class. By using the `super(name)` call, it invokes the constructor of the parent Dog class, allowing the Labrador class to inherit the properties defined there. This is crucial, as in JavaScript, when a class extends another class, it needs to call the parent class's constructor using the `super` keyword before attempting to set any properties of its own. In this case, the Labrador class constructor accepts two parameters: `name` and `size`. The first step within the constructor is to call `super(name)`, which initializes the `name` property in the Dog class. After that, the size property is set on the Labrador instance using `this.size = size`. This ensures that all required properties are correctly initialized when creating a new instance of Labrador. The other options lack this necessary invocation of the parent class constructor or mismanage the parameters, resulting in incomplete or incorrect inheritance behavior. This highlights the importance of using `super` when extending classes in JavaScript to ensure proper initialization of inherited properties.