Using JavaScript to invoke a child method within a parent class

Is it recommended to call a child method from a parent class in JavaScript? In the given example in BaseComponent.js, calling this.constructHtml() is returning undefined. What could be causing this issue? Thank you!

script.js

import Header from './components/Header.js';

const headerEl = document.querySelector('.header');

const header = new Header(headerEl);
header.render();

Header.js

import BaseComponent from './BaseComponent.js'

export default class Header extends BaseComponent {  
    
    constructor(element)
    {
        super(element);
        this.element = element;
    }

    constructHtml() {
        return  
        `
        <header>
            <h1>Todo App</h1>
        </header>
        `;
    }
}

BaseComponent.js

export default class BaseComponent {
    constructor(element) {
        this.element = element;
    }

    render(){
        this.element.innerHTML += this.constructHtml();
    }
}

Answer №1

Is it recommended to invoke a child method from a parent class?

Absolutely! It is considered standard practice. However, the parent class should either have a default implementation for constructHtml, or declare it as abstract (if using TypeScript). Specifically, it is advisable to call methods that are explicitly declared within the class itself, even if they are expected to be overridden in a subclass.

When calling this.constructHtml(), you may notice that undefined is returned.

This occurs because of a missing return; statement that doesn't provide a return value. Simply remove the line break and avoid using Allman brace style in JavaScript.

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

The onclick event is malfunctioning in Chrome when dealing with data driven by SQL

<select id='city' name='city' > <?php $dbcon = mysql_connect($host, $username, $password); mysql_select_db($db_name,$dbcon) or die( "Unable to select database"); $city_query = "SELECT city,county FROM citycatalog order by city ...

Activate animation while scrolling the page

I am using a progress bar with Bootstrap and HTML. Below is the code snippet: $(".progress-bar").each(function () { var progressBar = $(this); progressBar.animate({ width: progressBar.data('width') + '%' }, 1500); }); <body> & ...

Installing v8-profiler on Windows 8 (64 bit) through npm: a step-by-step guide

The v8-profiler module is widely recognized as the go-to tool for identifying memory leaks in node.js applications. However, attempting to install it with npm install v8-profiler results in an error message related to compatibility issues between 32bit an ...

Increasing a variable in MongoDB using Meteor.js based on the value of a variable in a separate document

I am facing an issue similar to this: I am struggling to modify multiple documents simultaneously. click: function() { var power = Meteor.user().power; var mult = Meteor.user().mult; Meteor.users.update({ _id: this.use ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

What could be the reason for the failure of Angular Material Table 2 selection model?

A Question about Angular Mat Table 2 Selection Model Why does the selection model in Angular Mat Table 2 fail when using a duplicate object with its select() or toggle() methods? Sharing Debugging Insights : Delve into my debugging process to understand ...

Reactjs encountered a problem with the click event

I seem to be facing a small issue with my react component code. I can't seem to figure out what's wrong. Here's the component code: import React, { Component, PropTypes } from 'react'; import styles from './Menu.css'; im ...

Webpack Error: SyntaxError - an unexpected token found =>

After transferring my project to a new machine, I encountered an error when running webpack --watch: C:\Users\joe_coolish\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:186 outputOption ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...

Tips for setting up offline alerts using a progressive web application

I have been working on implementing reminder notifications for my progressive web app, which was originally built as a Nextjs site. The specific criteria I need to meet are: Functionality even when the device is offline Accurate notifications within secon ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Displaying a table in Chrome/Firefox with a mouseover feature

Hovering over the rows of this table triggers a display of descriptions. html: <tr title="{{transaction.submissionLog}}" class="mastertooltip">... JavaScript: $('.masterTooltip').hover(function(){ // Hover functionality ...

Integrating an external JavaScript library into the codebase

I created a web radio player using Vue Cli and now I need to incorporate a new feature with an external library, specifically designed for handling audio advertisements. The catch is that this library must be loaded from a remote server and cannot be simpl ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

Retrieving Dropdown Value in Bootstrap 5: How to Obtain the Selected Item's Value from the Dropdown Button

I am having a slight issue with my dropdown button where I am trying to display the selected item as the value of the dropdown button. The Flag Icon and Text should be changing dynamically. I have tried some examples but it seems that it is not working as ...

Having trouble with my ajax request not functioning correctly

<body style="margin:0px; padding:0px;" > <form method="post" > <input type="text" id="city" name="city" placeholder="Enter city name"> <input type="submit" value="Search City" id="searchid"/> ...

Looking for a .NET MVC AJAX search solution. How can I enhance the code below?

I am looking to implement a search functionality using AJAX. I have tried using the get method in my controller by passing the search string, but it is not working as expected. Below is a snippet of my controller code, where I retrieve the search value fr ...

Customizing the attribute of an HTML tag using EJS or jQuery

Within my express server, I am rendering a page with the following data: app.get('/people/:personID', function (req, res) { res.render("people/profile", {person: req.person }); }); Inside my profile.ejs file, I can display the data within an ...

From Angular JS to Node Js with the help of the Express Js framework

I've been attempting to run an AngularJs front-end with a NodeJs server using ExpressJs. The main purpose of this program is to take user input and display it on the server console. With my limited JavaScript knowledge, I've put together the foll ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...