Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed.

Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization.

However, the behavior of the second child class is not what I expected. The only distinction between the two classes is the declaration of a member variable. In typical JavaScript, I would not approach it this way, but since I'm using Typescript, the compiled result includes a "member;" (in my case, even without assigning a value). Consequently, the output shows "undefined".

I suspect this issue arises when the variable is set within an overridden function called by the parent constructor.

Could someone shed some light on why this anomaly occurs?

class Parent {
    constructor(initArgs) {
        this.init(initArgs);
    }

    init() {}
}

class ChildTest1 extends Parent {
    init(args) {
        this.member = args;
    }

    test() {
        console.log(`Member of ChildTest1 has value of "${this.member}"`);
    }
}

class ChildTest2 extends Parent {
    member = "default";;

    init(args) {
        this.member = args;
    }

    test() {
        console.log(`Member of ChildTest2 has value of "${this.member}"`);
    }
}

new ChildTest1("Hello World").test();
new ChildTest2("Hello World").test();

The code produces the following output:

Member of ChildTest1 has a value of "Hello World"

Member of ChildTest2 has a value of "default"

Answer №1

When initializing your variable, it gets overwritten in the process. The sequence of property initialization and constructor execution is crucial:

  1. The parent class constructor runs first and sets member to Hello World

  2. Then, the properties of your child class are initialized, replacing the previously set member variable.

  3. Finally, the child class constructor is executed.

To illustrate this point clearly, I've modified your code slightly (adding the child constructor for clarity), check it out below:

class Parent {
    constructor(initArgs) {
        this.init(initArgs);
        console.log(`Parent Constructor: Member of ChildTest2 has value of "${this.member}"`);
    }

    init() {}
}

class ChildTest2 extends Parent {
    member = "default";

    constructor(initArgs) {
        super(initArgs);
        console.log(`Child Constructor: Member of ChildTest2 has value of "${this.member}"`);
    }

    init(args) {
        this.member = args;
        console.log(`Init: Member of ChildTest2 has value of "${this.member}"`);
    }

    test() {
        console.log(`Test: Member of ChildTest2 has value of "${this.member}"`);
    }
}

new ChildTest2("Hello World").test();

Output will be:

[LOG]: "Init: Member of ChildTest2 has value of "Hello World"" 
[LOG]: "Parent Constructor: Member of ChildTest2 has value of "Hello World"" 
[LOG]: "Child Constructor: Member of ChildTest2 has value of "default"" 
[LOG]: "Test: Member of ChildTest2 has value of "default""

Understand that property initialization occurs after the super(...) call within the constructor. For further details, refer to this resource

Answer №2

configure tsconfig

"allowSyntheticDefaultImports": true,

improves functionality

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

Trouble keeping HTML/Javascript/CSS Collapsible Menu closed after refreshing the page

My issue is that the collapsible menu I have created does not remain closed when the page is refreshed. Upon reloading the page, the collapsible menu is always fully expanded, even if it was collapsed before the refresh. This creates a problem as there is ...

Adding a proptype for a setState method in React components

I am currently developing a reusable component for a project. This particular component includes user and setUser as props, much like the example provided below. const UserComponent = ({ user, setUser }) => { const calcHandler = useCallback(() =& ...

Is it feasible for the Drawer to be a fixed feature that sits atop the content?

I am looking to have a compact drawer positioned on the left side of my screen, similar to the example shown in the Material UI Documentation: https://i.sstatic.net/W21Kd.png However, I would like it to float over the content (like the variant="temporary ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Implementing conditional where clauses in Firestore queries with dynamic parameters

Consider this scenario: I have a dynamic filter list for my product list, and I want to send an HTTPS request to a cloud function based on the selected filters. However, when trying to set multiple conditional where clauses from that request... The multip ...

Tips for adjusting the height of a Safari extension during runtime

After successfully developing a Safari extension, I am facing an issue with adjusting the width and height of the popover dynamically at runtime. Can anyone provide insights on how to modify the dimensions of the popover based on its content? ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

Using embedded js files in jQuery's .load() function does not function properly

In the index.html file, I have the code snippet below: <div id="page-insert"></div> function openPage(pageid) { $('#page-insert').load(pageid); } openPage('testpage.html'); Additionally, there are script files embedde ...

Steps to prevent specific links from being clickable in React Native's webview component

In my React Native app, I am utilizing the react-native-webview component to display blog posts. The code I have implemented is straightforward, but my goal is to restrict the webview to only show content from the blog section of the website, preventing us ...

Retrieve the item within the nested array that is contained within the outer object

I have a collection of objects, each containing nested arrays. My goal is to access the specific object inside one of those arrays. How can I achieve this? For instance, take a look at my function below where I currently log each array to the console. Wha ...

Tips for getting Angular's HttpClient to return an object rather than a string?

How can I make HttpClient return the data in JSON Object format? The Angular documentation states that HttpClient should automatically parse returned JSON data as an object. However, in my project, it only returns the data as a string. Although using JSO ...

Testbed: Issue encountered: Unable to resolve all parameters for PriDateInput component

I am facing an issue while creating an Angular Component with the help of TestBed. The error message I receive is as follows: Error: Can't resolve all parameters for PriDateInput: (?). error properties: Object({ ngSyntaxError: true }) ...

"Is there a way to reverse the action of $( "button" ).remove()

Currently, I have implemented JQuery's $( ".button" ).remove(); function to get rid of all the buttons on my webpage immediately after a user clicks the print PDF button that changes the HTML page into a PDF. Nevertheless, once this process is done ...

Developing a dynamic slideshow using jQuery

I'm working on a website where I want an image to change when I click on a specific piece of text. Currently, I have set up a class called "device" with one of them having the class "active" like this: <div class="col-md-3"> <div c ...

Discovering relative URLs within an MVC 4 framework

Seeking a solution for storing the fully qualified URL of a relative path in MVC: ~/Content/themes/base/jquery-ui.min.css" In my scenario, I have a hidden input field: <input type="hidden" id="siteUrl" value=""/> I attempted to populate this hidd ...

Showing formatted JSON (Large Object) on an HTML page

Having trouble displaying formatted JSON in an HTML page, especially when dealing with larger objects (an array of objects). The current method involves using JSON.stringify(data) to display the JSON object upon receiving a response from the server. The P ...

What is causing it to give me 'undefined' as the result?

Trying to execute a script, test.al(); and within test.al, it calls getcrypt.php();. The php script is hosted on a webserver, and it is functioning properly. Here are the current scripts being used: JS var getcrypt = { php: function () { $.a ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...

Get Facebook to recognize and display link previews for websites using ajax technology

It is commonly known that when copying a link from an HTML website onto Facebook, the platform will attempt to fetch available images as previews for the link. But what happens when the content is dynamically generated, such as with JavaScript? In this c ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...