Calling Parent Constructors with super
When you create a subclass in JavaScript using the extends keyword, the subclass inherits properties and methods from its parent class. However, to properly initialize the parent class's properties within the subclass's constructor, you must use the super keyword. The super keyword acts as a reference to the parent class's constructor and allows you to call it from within the subclass. This is essential because, in JavaScript, a subclass constructor cannot access this until after it has called super. By calling super, you ensure that all properties defined in the parent class are correctly set up before you add or modify properties specific to the subclass. This mechanism not only enables property inheritance but also allows you to extend or customize the initialization process for your subclasses.
1234567891011121314151617181920// Parent class class Vehicle { constructor(make, model) { this.make = make; this.model = model; } } // Subclass class Car extends Vehicle { constructor(make, model, doors) { super(make, model); // Call parent constructor this.doors = doors; // Additional property for Car } } const myCar = new Car("Toyota", "Corolla", 4); console.log(myCar.make); // Output: Toyota console.log(myCar.model); // Output: Corolla console.log(myCar.doors); // Output: 4
¡Gracias por tus comentarios!
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla
Awesome!
Completion rate improved to 6.25
Calling Parent Constructors with super
Desliza para mostrar el menú
When you create a subclass in JavaScript using the extends keyword, the subclass inherits properties and methods from its parent class. However, to properly initialize the parent class's properties within the subclass's constructor, you must use the super keyword. The super keyword acts as a reference to the parent class's constructor and allows you to call it from within the subclass. This is essential because, in JavaScript, a subclass constructor cannot access this until after it has called super. By calling super, you ensure that all properties defined in the parent class are correctly set up before you add or modify properties specific to the subclass. This mechanism not only enables property inheritance but also allows you to extend or customize the initialization process for your subclasses.
1234567891011121314151617181920// Parent class class Vehicle { constructor(make, model) { this.make = make; this.model = model; } } // Subclass class Car extends Vehicle { constructor(make, model, doors) { super(make, model); // Call parent constructor this.doors = doors; // Additional property for Car } } const myCar = new Car("Toyota", "Corolla", 4); console.log(myCar.make); // Output: Toyota console.log(myCar.model); // Output: Corolla console.log(myCar.doors); // Output: 4
¡Gracias por tus comentarios!