What causes the `super` keyword property to return undefined within an ES6 class?

As a newcomer to ES6 classes, I am exploring how inheritance functions within it. To experiment with this concept, I have constructed a parent class named Modal and a child class called ChildModal. Below is the content of these classes:

class Modal {
    constructor(selector, document) {
        this.selector = selector;
        this.document = document;
    }

    get title() {
        return this._title;
    }

    set title(title) {
        if(!title) {
            throw new Error('Original title cannot be empty');
        }
        this._title = title;
    }

    defineNewTitle(newContent) {
        this.title = newContent + this.title;
    } 

    assignNewTitle() {
        $(this.selector).text(this.title);
    }
}

var modal = new Modal("#mainTitle");

modal.title = "Standards";

modal.defineNewTitle("JavaScript ");

modal.assignNewTitle();

class ChildModal extends Modal {
    constructor(selector, title) {
        super(selector, title);
    }

    defineChildTitle(title) {
        this.title = title + this.title;
    }

    assignChildTitle() {
        $(this.selector).text(this.title);
    }
}

var child = new ChildModal("#childTitle");
child.defineChildTitle("Wow ");
child.assignChildTitle();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Class test</title>
<h1 id="mainTitle">
Main title
</h1>
<h2 id="childTitle">
Child title
</head>
<body>
<script src="Modal.js"></script>
</body>
</html>

In my implementation, I anticipate the h2 tag to display 'Wow JavaScript Standards', yet it currently shows 'Wow undefined'. The issue lies in the defineChildTitle method where this.title is not being recognized. Despite inheriting from the Modal class in the constructor function of ChildModal, why does this.title not reflect as 'JavaScript Standard' as expected?

Answer №1

Each instance of a class has its own unique set of fields, such as title, selector, and document. This means that assigning a title to one variable does not affect any other instances or classes.

When the ChildModal class calls super(selector, title), it passes its title argument to the constructor of the Modal class. The title is then stored in the document field of the Modal class.

However, if you attempt to concatenate the title with itself using this.title = title + this.title;, the title field will be undefined. As a result, the final value of the title ends up being "Wow" + undefined, which equals "Wow undefined".

Answer №2

Make sure to set the _title variable in your constructor:

class Modal {
    constructor(selector, document) {
        this.selector = selector;
        this.document = document;
        this._title = ''
    }
}

var child = new ChildModal("#childTitle");
child.title = "JavaScript Standards"
child.defineChildTitle("Wow ");
child.assignChildTitle();

You are currently combining a string with undefined, which results in undefined.

Since you are creating two separate instances, they do not share the same data. Therefore, child.title is not equal to modal.title, resulting in different strings when concatenated together.

To resolve this issue, you must not only set the title using

modal.title = 'JavaScript Standards'
, but also ensure that
child.title = 'JavaScript Standards'
.

class Modal {
    constructor(selector, document) {
        this.selector = selector;
        this.document = document;
        this.title = ' '
    }

    get title() {
        return this._title;
    }

    set title(title) {
        if(!title) {
            throw new Error('Title cannot be empty');
        }
        this._title = title;
    }

    redefineTitle(newContent) {
        this.title = newContent + this.title;
    } 

    applyNewTitle() {
        $(this.selector).text(this.title);
    }
}

var modal = new Modal("#mainTitle");

modal.title = "Standards";

modal.redefineTitle("JavaScript ");

modal.applyNewTitle();

class ChildModal extends Modal {
    constructor(selector, title) {
        super(selector, title);
    }

    defineChildTitle(title) {
        this.title = title + this.title;
    }

    assignChildTitle() {
        $(this.selector).text(this.title);
    }
}

var child = new ChildModal("#childTitle");
child.title = "JavaScript Standards"
child.defineChildTitle("Wow ");
child.assignChildTitle();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Class test</title>
<h1 id="mainTitle">
Main title
</h1>
<h2 id="childTitle">
Child title
</head>
<body>
<script src="Modal.js"></script>
</body>
</html>

Answer №3

When it comes to ES5 classes, they still rely on prototype.

An alternative approach could involve changing modal.title = "Standards"; to

Modal.prototype.title = "Standards";
.

By doing this, you are not modifying the property in the instance directly, but rather altering the value in the prototype (which is essentially the class definition):

class Modal {
    constructor(selector, document) {
        this.selector = selector;
        this.document = document;
    }

    get title() {
        return this._title;
    }

    set title(title) {
        if(!title) {
            throw new Error('Original title cannot be empty');
        }
        this._title = title;
    }

    defineNewTitle(newContent) {
        this.title = newContent + this.title;
    } 

    assignNewTitle() {
        $(this.selector).text(this.title);
    }
}

var modal = new Modal("#mainTitle");

Modal.prototype.title = "Standards";

modal.defineNewTitle("JavaScript ");

modal.assignNewTitle();

class ChildModal extends Modal {
    constructor(selector, title) {
        super(selector, title);
    }

    defineChildTitle(title) {
        this.title = title + this.title;
    }

    assignChildTitle() {
        $(this.selector).text(this.title);
    }
}

var child = new ChildModal("#childTitle");
child.defineChildTitle("Wow ");
child.assignChildTitle();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<title>Class test</title>
<h1 id="mainTitle">
Main title
</h1>
<h2 id="childTitle">
Child title
</head>
<body>
<script src="Modal.js"></script>
</body>
</html>

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

What is preventing the item from utilizing the custom texture I created?

(Using IntelliJ to code everything) I am currently working on a Minecraft Mod and have encountered a strange issue. When testing my custom item, the name displays perfectly with spaces, but the texture fails to load. The error message I receive is as follo ...

Optimizing AngularJS ui-router to maintain state in the background

Currently working on an AngularJS project that involves a state loading a view containing a flash object. I am looking for a way to ensure that the flash object remains loaded in the background during state changes, preventing it from having to reload ev ...

Whenever I execute my code, the browser consistently crashes

Here is the code I have been working on: var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg", "image5.jpg", "image6.jpg", "image7.jpg", "image8.jpg"]; var objects = []; var geometry; while(objects.length < images.length) { va ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Javascript code for populating multiple objects with new items using a nested for loop

Trying to articulate my thoughts, I am interested in linking a list of skill sets to various individuals within their respective lists. For instance: I possess a Json object detailing individuals: "people": [ { "id": 1, "name": "Tony ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

Having trouble passing multiple associative array values from JavaScript/AJAX to PHP

We have been encountering an issue when trying to pass multiple associative array values from JavaScript/AJAX to PHP, as the PHP file is receiving an empty object/array. Could someone kindly assist us in retrieving the values of an associative array from ...

Discovering access to this.$i18n.locales from store getter in Nuxt, i18n, and Vuex

Currently, I am constructing a web application utilizing Nuxt v2.15 and @nuxtjs/i18n v7.2 while employing Vuex for state management. Within my global state, I aim to develop a getter that retrieves a value reliant on this.$i18n.locale. How can I effective ...

Searching for a JavaScript button via aria-label and interacting with it using Python Selenium

I am currently utilizing Python Selenium to locate and interact with a specific javascript button on a webpage. The solutions provided in various forums do not suit my needs as the button I am targeting is unique. To begin, I will display an image of the p ...

What is the most effective method for displaying an error code when a JavaScript error occurs?

I'm currently dealing with a library that is throwing errors: throw new Error('The connection timed out waiting for a response') This library has the potential to throw errors for various reasons, making it challenging for users to handle ...

Is there a way to ajax just specific HTML table rows instead of transmitting all the form inputs?

For weeks, I've been struggling to use AJAX POST with a JSP script to update my HTML table rows without success. Can anyone provide guidance on this? Below is what I have attempted so far. window.addEventListener("DOMContentLoaded", function () { ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...

Implementing Text Box Control Validation within a Gridview using UpdatePanel in c# ASP.Net

In my gridview, one of the columns contains a Text Box Control. I am looking to validate the text entered by users as alphanumeric characters and spaces only. Allowed characters are: a-z, A-Z, 0-9, and space. I want to perform this validation using Java ...

Yii is interpreting the URL to point to a specific controller and action instead of directly running the script

The current codebase I am maintaining relies on Yii v1.0 and uber uploader for file uploads. The process involves triggering the uber uploader's Perl script through a jquery.post method within a js file. This is being implemented on a GoDaddy Linux vi ...

updating dropdown options based on user input with PHP

I need help with implementing a code for two dropdown boxes. The first dropdown should display main category values dynamically, and when a value is selected, the second dropdown should appear with corresponding sub-category values. How can I achieve this ...

Utilizing encoding and decoding techniques in PHP and JavaScript with robust data attribute validation

I am utilizing data attributes to transfer information from HTML to JavaScript. The data attributes are derived from MySQL data, so they may contain spaces, resulting in validation errors since spaces are not permitted within attributes. My proposed solut ...

Looking for a substitute for iframes when using jQuery UI tabs?

I currently have a Spring-based web application that integrates with jQuery Tabs. What I'm doing is building a data string with specific parameters and appending it to a URL: var hrefData = "?" + item1 + "&" + item2 + "&" + item3; var href = ...

It seems that there is a null value being returned in the midst of the

I have developed a model using express. While setting this in one function, it returns null in another function, forcing me to use return. What is the proper method to handle this situation? const Seat = function(seat) { this.seat = seat.seat; this. ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

"Encountering a hiccup with the Firebase service worker in Messaging and Firebase

I am interested in developing a small web application to explore the capabilities of Firebase Cloud Messaging for web apps. My intention is to utilize Firebase Hosting as the hosting platform for my app. ISSUE: Upon allowing the notification pop-up on my ...