ES6 - The importance of 'super' in a constructor method

class Overflow {}
class Stack extends Overflow {
  constructor() {
    super();
  }
}

let stack = new Stack();

https://plnkr.co/edit/JqRfuDAav9opvapwCGpT?p=preview

If I utilize construtor(), it is absolutely necessary to always call super().

Have you also wondered why super() is not automatically invoked in the constructor?

Edit: Does super() here activate the base constructor and configure the prototype as well? Seems incorrect. Edit: What is the rationale behind requiring super()? Even when I don't plan on calling the base constructor.

Answer №1

Why doesn't the constructor automatically call super()?

The reason for this is so that you have the flexibility to decide where in the constructor to make the call. You can choose when and how to initialize the parent class. For example:

constructor(foo) {
    let bar;
    if (foo) {
        bar = /*...*/;
    } else {
        bar = /*...*/;
    }
    super(bar);
}

This approach is allowed as long as no code before the super call references this or super.xyz.

The language could have been designed to automatically add a call to super at the beginning of the constructor if it wasn't present at all, similar to Java. However, this decision was intentional.

Does super() both call the base constructor and set the prototype? It seems incorrect.

No, super() only calls the base constructor. The prototype is established before your constructor is invoked. This behavior mirrors the way it would be done in older ES5 syntax like this:

function Derived() {
    Base.call(this);
}

....where:

function Base() {
}

function Derived() {
    Base.call(this);
}
Derived.prototype = Object.create(Base.prototype);
Derived.prototype.constructor = Derived;

Why is super() necessary even when I don't plan on calling the base constructor?

If you have no intention of calling the base constructor, then perhaps your subclass shouldn't actually be extending the base class. In a statically-typed language, you might consider making the base class an interface instead. In JavaScript, you have more flexibility - you can make your subclass behave like the desired object without having to extend its functionality. If maintaining an instanceof relationship is crucial, you can create a new "dummy" base that acts as an interface for type checking purposes.

Answer №2

Julia is the best

Overview

What is the significance of using super keyword?

  • The new keyword class has more functionality than just being syntactic sugar.
  • Memory allocation and object instantiation only occurs in the base constructor.

But why is this necessary?

  • In order to facilitate extension of exotic objects (appreciation goes to Felix Kling).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you have more than one ID at a time?

Similar Question: Is it valid for an HTML element to have multiple IDs? Can a single HTML element have multiple IDs? Is the following code snippet a correct way to use multiple IDs? $("#example" + " #example2") HTML Code: <section id="example ex ...

The challenge of having to manually refresh the browser each time an update is made using a put request in

When the user enters a name and number and clicks the add button, the new person's information is automatically added to the database. If the name already exists, a prompt will ask, 'name is already in the phonebook, do you want to update it with ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Error message saying 'Callback has already been invoked' returned by an async waterfall function

I'm facing an error that I understand the reason for, but I'm unsure how to resolve it. Here's a breakdown of my initial function: Essentially, I am making a get request for all URLs stored in the database and then, for each URL response, I ...

How can you prevent specific dates from being selected in an Angular Datepicker?

Is there a way to exclude Monday from the "mat-datepicker" component? I've tried implementing the following code in my class component: dateFilter = (_date: any) =>{ let day = _date.getDay(); console.log(day); return day != 1; ...

Having trouble with Append() function not functioning properly within the if statement nested inside a .each loop in jQuery

Looking to add text after the 4th element in a ul li? I tried using the append function, but it's appending before every li element. Here's the HTML: <ul class="gallery"> <li><a href="#">Some Text</a> ...

Generating a two-dimensional array and setting its values in JavaScript

I need assistance with creating and initializing a two-dimensional array in JavaScript within an AngularJS application. My current approach is as follows: $scope.invalidVote = []; for (var i = 0; i < $scope.arry1.length; i += 1) { $scope.answersCou ...

Having trouble with the Javascript denial of submit functionality?

I'm dealing with an issue in my code where form submission is not being denied even when the input validation function returns false. I can't figure out what's causing this problem. <script> function validateName(x){ // Validati ...

loop through array and assign values to elements

Is it possible to assign the values of a, b, c to each li? Right now, with my current code, I am only able to get all c. arr = ['a','b','c']; arr.forEach(function(obj){ var x = obj; $('li').each(function () { ...

Invoking a function from an external JavaScript file

Looking for a way to call a function from an external JavaScript file? Here are the specifics: Within the head tag, include the following script: <script type="text/javascript" src="JScript/FontSize.js"></script> The FontSize.js file yo ...

What is the best way to create a compound query in Firebase?

I am working on a TypeScript script to search for a city based on its population... import { getFirebase } from "react-redux-firebase"; ... get fb() { return getFirebase(); } get fs() { return this.fb.firestore(); } getCollection(coll ...

Filtering by two expressions using $filter in AngularJS

Check out the documentation for the $filter function here: https://docs.angularjs.org/api/ng/filter/filter To achieve my goal, I currently use the following code: $scope.images = $filter('filter')(imageList, { type: 'snapshot' }); $sc ...

Enable Class exclusively on upward scrolling on the browser

Is there a way to dynamically change the class of an element only when the user scrolls the browser page upwards? Issue Filide>> JavaScript $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll <= 100) { ...

The functionality of the Vueify modal seems to be malfunctioning when incorporating Vueify alongside a central Modal.vue file that houses modal templates

I've been experimenting with integrating this tutorial on creating reusable modal dialogs with Vuejs and adapting it for use with Vueify. Initially, I was able to successfully implement it, but after exploring a different approach briefly, I returned ...

Ways to prevent body scrolling when the mobile menu is open

Is there a way to prevent the body from scrolling when I open a menu on a mobile device? function stopBodyScrollOnMenuOpen() { $('.header .navbar .navbar-toggler i').on('click', function (event) { $('body').toggleClass( ...

Using AngularJS, we can create a nested ng-repeat with an expression to filter the

I'm having trouble using a value from the initial ng-repeat as a filter in the nested ng-repeat. The issue lies with {{alpha.value}}. It displays correctly in the first repeat, including the filter and the h3 tag. However, in the second repeat, it s ...

Unraveling nested elements with the array map() method in Angular2 and Typescript: Fixing the issue of undefined property reference while mapping

Hey there! I'm currently working with Angular 4 and I have a piece of code that parses data from an API into a TypeScript array of rows. It's important to note that the code functions properly if elements like 'item.tceCampRun' and &apo ...

Applying various Angular filters to an array of objects within HTML select elements

I'm fairly new to working with JS and the rather challenging learning curve of AngularJS. I have an array containing numerous objects with the relevant properties listed below: $scope.myRecs = [{country: 'Ireland', city: 'Dublin&apos ...

Validation of forms using ajax and javascript

I have implemented ajax on my webpage to dynamically change the content of a main div when different fields in the navigation bar are clicked. However, I am encountering a problem with form validation using JavaScript on elements loaded via ajax. For insta ...

Could Express be considered the most reliable and efficient application framework for NodeJS?

While I have some experience with Express, I haven't explored many other Node-based web application frameworks. It's clear that Express is lightweight and versatile, but my usage has been limited to small experimental projects rather than large-s ...