Passing Down Instance Methods Using Static References in JavaScript/TypeScript

✋ Exploring the concept of access modifiers from TypeScript, how can we make it relevant for JavaScript developers as well? Let's consider a scenario where a parent class defines necessary members and a shared method:

// ParentClass.js
export default class ParentClass {
  private static voo;
  private bar;

  constructor(bar) {
    this.bar = bar;
  }

  private commonMethod(baz) {
    doSomething(ParentClass.voo);
    doSomethingElse(this.bar, baz);
  }
}

Now, let's look at a child class that inherits this behavior:

// ChildClass.js
export default class ChildClass extends ParentClass {
    voo = "Jake";

    constructor(bar) {
        super(bar)
    }

    public uniqueMethod(ter) {
        doAnotherThing(this.bar);
        this.commonMethod(ter);
    }
}

When calling commonMethod() within ChildClass.uniqueMethod(), it references the value of ParentClass.voo, which is undefined. How can we ensure that each inheriting child class uses the same implementation of the method but references the static member of the child class itself? Is there a solution available for this issue?

One workaround would be to make voo an instance member instead of a static member, but if a static voo is more useful in certain scenarios, what other solutions are possible?

I've shared my current solution in response to this question, but I am curious if there is a more direct approach to address this challenge.

Answer №1

Currently, my approach involves attaching an instance accessor and modifying the commonMethod() to utilize that accessor:

// ParentClass.ts
export default class ParentClass {
  private static _voo;
  private bar;

  constructor(bar) {
    this.bar = bar;
  }

  public get voo() {
    return ParentClass._voo;
  }

  private commonMethod(baz) {
    doSomething(this.voo);
    doSomethingElse(this.bar, baz);
  }
}

Subsequently, inheriting classes override the accessor:

// ChildClass.ts
export default class ChildClass extends ParentClass {
    _voo = "Jake";

    constructor(bar) {
        super(bar)
    }

    public override get voo(){
        return ChildClass._voo
    }

    public uniqueMethod(ter) {
        doAnotherThing(this.bar);
        this.commonMethod(ter);
    }
}

This method doesn't strike me as particularly elegant, so I welcome any feedback or suggestions on alternative approaches.

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

Using PHP's for loop to iterate through data and store them into arrays

Attempting to transmit data from JavaScript to a PHP file through an AJAX request, and then store each result in an array using PHP. queryData={"data":{"data_string":{"data":"medicine","default_field":"Content"}}} testArgument=0; $.ajax({ url:"test/q ...

What's preventing my Angular list from appearing?

I am currently developing an Angular project that integrates Web API and entity framework code first. One of the views in my project features a table at the bottom, which is supposed to load data from the database upon view loading. After setting breakpoin ...

The browser is struggling to interpret the incorrect HTML content

I am looking for a way to create a function that can retrieve account data from my database and organize it in a user-friendly HTML table where users can make selections and modifications. The code I have so far is as follows: $.ajax({ url: "./dat ...

Reactjs: Prop Type Error - Issue with retrieving the values from props during data submission

Currently, I am developing a social app where users can post screams, like posts, and add comments. The issue I'm encountering is that I am not receiving the props value when posting a new scream initially, but after refreshing the page, everything wo ...

What is the best way to apply the addClass method to a list element

I've been searching for a solution to this issue for some time now, and while I believed my code was correct, it doesn't appear to be functioning as expected. HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...

Initiate the execution of JavaScript functions in the loaded partial view using Ajax

I am currently working with a javaScript function that loads a partial view within my page's layout using the following logic: $('.follow-tasks').click(function (e) { e.preventDefault(); var $followtaskList = $("#td-" + $(this).attr ...

Performing height calculations in JavaScript is necessary to recalculate them whenever there is a

A JavaScript function is used to calculate the height of an iframe element and the document height, then determine if the iframe is on or off based on its height and display properties. The issue arises when changing pages— if the height is less than the ...

obtaining the controller output in JavaScript

Scenario: Retrieving id in javascript following an ajax post I'm trying to figure out how to access the id sent from my controller's ActionResult in javascript. I've experimented with both Content Result and JSON Result on the controller, b ...

Is the behavior of String.replace with / and different in Node.js compared to Chrome?

Creating a router in Node.js involves mapping URIs to actions, which requires an easily configurable list of URIs and regular expressions to match against the request URI. This process may seem familiar if you have experience with PHP. To test this functi ...

Remove a particular row from a database table

I'm facing an issue with my code. I want to be able to remove a row by clicking on a remove button within that row, but I'm unsure of how to accomplish this. <tbody id="myTable"> <?php if (!isset($_SESSION)){ ...

When attempting to utilize a global variable in a POST request, it may be found to

My dilemma is that I can successfully access the global variable in other requests such as 'GET', but it becomes undefined when used in a 'POST' request. var dirName; app.post("/addFace", function (req, res) { //create directory con ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...

"Struggling with setting the default checked state for single and multiple checkboxes? The ng-init method with checkboxModel.value=true seems to be ineffective – any suggestions

<input type="checkbox" ng-model="isChecked.value" ng-true-value="'yes'" ng-false-value="'no'" ng-click='handleCheckboxChange(isChecked.value, idx);' ng-init="isChecked.value=true" /> ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Display the number of rows per page on the pagination system

Looking for a way to add a show per page dropdown button to my existing pagination code from Mui. Here's the snippet: <Pagination style={{ marginLeft: "auto", marginTop: 20, display: "inline-b ...

Exploring the method of accessing one Vue plugin from another plugin with the use of Vue.prototype

I'm currently working on developing a Vue plugin aimed at simplifying the management of authentication state throughout my application. This particular plugin will require interaction with other Vue plugins such as vuex, vue-router, and vue-apollo (fo ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Encountering an error with the Typescript 'any' type in Ionic 2

I need help understanding an error I encountered: EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in build/pages/search/search.html:17:14 ORIGINAL EXCEPTION: Cannot find a differ supporting object 'function () { return [ { ...

effortlessly eliminate the Google MyMap watermark from an iframe using ReactJS

I am new to ReactJS and I would like help on how to hide the watermark on a Google My Map. Can someone please assist me with this? <iframe src="https://www.google.com/maps/d/u/1/embed?mid=1OMSkPKZi-U-CnmBr71zByNxp8HYi-vOc&ehbc=2E312F" fram ...