ES6: utilizing properties and methods of a subclass that inherit from the superclass

While ES6 does not have abstract methods or properties, is it possible to access some methods or properties from the parent class in an inherited class?

class ParentClass {

    constructor(){

      ParentClass.checkChildPropertyAccessibility();
      ParentClass.checkChildMethodAccessibility();

      ParentClass.checkChildStaticPropertyAccessibility();
      ParentClass.checkChildStaticMethodAccessibility();

    }

    static checkChildPropertyAccessibility() {
        console.log(ParentClass.childProperty);
    }

    static checkChildMethodAccessibility(){
        ParentClass.childMethod()
    }

    static checkChildStaticPropertyAccessibility(){
        console.log(ParentClass.childStaticProperty);
    }

    static checkChildStaticMethodAccessibility(){
        ParentClass.childStaticMethod()
    }
}

class ChildClass extends ParentClass {

    constructor(){
        super();
        ChildClass.childProperty = 'child\'s Property: OK';
    }

    childMethod(){
        console.log('child\'s method OK');
    }

    // static property emulation in ES6
    static get childStaticProperty() { return 'Child\'s static property: OK even in ES6' }

    static childStaticMethod (){
        console.log('Child\'s static method: OK');
    }      
}

let childClassInstance = new ChildClass(); 

The idea here is that "we need to define certain properties and methods in the child class, however, the parent class should already be able to access them in the constructor".

Answer №1

Absolutely, it is indeed possible to invoke methods that are exclusively defined in a subclass of an ES2015 class.

class ParentClass {

  constructor() {
    this.childMethod();
    this.initialize();
    console.log(this.childProperty1);
    console.log(this.childProperty2);
  }
}

class ChildClass extends ParentClass {

  constructor() {
    super();
    this.childProperty1 = 'child\'s Property: OK';
  }

  initialize() {
    this.childProperty2 = 'child\'s Property 2: OK';
  }

  childMethod() {
    console.log('Child\'s overriden method: OK');
  }
}

let childClassInstance = new ChildClass();

It's worth noting that initialize() is utilized to assign an initial value to childProperty2. The parent constructor will always execute before any other code in the subclass constructor, hence why childProperty1 isn't initialized when the console call was made. In the parent class, this will refer to an object with the prototype of the subclass. In the comments section, Bergi highlights the practice of invoking an overridden method in a parent constructor should be avoided, as the overridden method may rely on state not yet established by the child constructor.

On the flip side, it does not function with static methods. When referencing ParentClass, you will access the method defined there. There is no prototype chain to trace back to in this scenario.

UPDATE: clarification from comments section.

Answer №2

In static methods, the current constructor in a parent class can be referenced as this, while in instance methods it can be referenced as this.constructor.

This can create a potential design issue because the ParentClass does not have the methods and properties defined in the ChildClass. When trying to call a non-existent childMethod on a new instance of ParentClass, an error will occur.

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 the best way to reference a nested jQuery variable, whether global or local, within an HTML document

I've been working on this problem for days with no success. Any help would be greatly appreciated. I'm trying to call a variable from nested jQuery into HTML. The variable is named "PROBLEM". Even after trying to make it global, any updates made ...

Combine the elements within the HEAD tag into a group

I am currently developing a dynamic page system using AJAX. Whenever a link is clicked, an AJAX call is made to retrieve data from the requested page. However, I have encountered an issue where certain data in the page file needs to be placed within the h ...

Incorporating JavaScript Object-Oriented Programming in PHP

As someone new to JS programming, I am tasked with developing a php web application that relies on ajax calls for all actions without reloading the page. While I have completed the php and JS code, I am struggling to understand what JS OOP entails. My coun ...

The Link tag in the Hero.jsx file of Next.js is malfunctioning and failing to redirect to the intended URL

Having a problem with the button in my Hero.jsx component, part of the Page.js implementation. The button uses a Link tag to redirect to the url.js page, but it's not working as expected and showing an Error 404 page instead. I'm new to Next.js s ...

Understanding the process of accessing data within the beforeRouteLeave component guard in Vue

Having trouble accessing data within beforeRouteLeave as everything appears to be undefined Check out the code snippet below: <template> ... </template> <style lang="scss"> ... </style> <script> export default { ...

Switch the style sheets after the content

How can I create a toggle effect on the :after property, switching between + and - each time the link is clicked? I've attempted to achieve this using JavaScript, CSS, and HTML, but the code only changes + to - and doesn't switch back when the l ...

Having difficulty interpreting the responseText

Currently experimenting with Redis Webdis Dart Here's my code snippet #import('dart:html'); #import('dart:json'); class ChatClient { XMLHttpRequest listener; int parsePosition = 0; void connect(){ this.listener = ne ...

What is the best way to iterate through an array of images and upload them individually, ensuring that they do not have duplicate names

In my current code snippet, I am working with an array of images called images and uploading each image within that array. Everything seems to be working correctly, but I am encountering a minor issue where all the uploaded images end up having the same na ...

Tips for merging ajax div elements

Here's a combination of my Ajax scripts, integrating the first and second versions: 1st <script> function Ajax() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Transferring an object from the factory to the controller

I'm currently working on setting up a factory that sends an ajax request to an API and then returns a data object. Here is the code snippet I have written: app.factory('Test', function($http, $q) { var data = {response:{}}; var getM ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Surprising results from implementing the useLocation() hook in a React application

Currently, I am embarking on a personal endeavor to create an online auction platform. One of the key functionalities I am working on is rendering detailed product information when a user clicks on a specific product for purchase. Initially, everything wor ...

The process of ensuring a component updates upon clicking on it

In the process of creating a to-do app, I am working on implementing an edit mode for tasks. My goal is to have a task title that expands into task details when clicked (using Collapse from MUI). Additionally, I aim to enter into an edit mode by clicking o ...

Popups generated on the fly without any triggers from links

I'm populating a listview with items from localStorage. When a user clicks on a list item, a corresponding popup should appear. I already have a working solution where the popups are displayed upon request. However, this time I am dynamically adding t ...

How to access the public folder in React from the server directory

I am having an issue with uploading an image to the react public folder using multer in NodeJs. Everything was working fine during development, but once I deployed it, the upload function stopped working. It seems like the multer is unable to reference or ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Running multiple server and client codes on node.js simultaneously

I'm exploring the idea of establishing a network of nodes on my computer that have dual functionality as both clients and servers. Each node should be able to execute its unique server code and client code, allowing it to send requests to its individu ...

The code line "npx create-react-app myapp" is not functioning as expected

When running the command 'npx create-react-app my-app', I encountered the following error message: Error: '"node"' is not recognized as an internal or external command, operable program or batch file. Before suggesting to cre ...