Tips on invoking a static method in JavaScript subclass

Is it possible to call a static method of a subclass from a static method of the parent class?

class A {

  static foo(){
    // call subclass static method bar()
  }
}

class B extends A {

  static bar(){
    // do something
  }
}

B.foo()

Note:

I initially attempted this because subclasses of A would have functioned best as singletons in my specific context, and I wanted to implement the template method pattern within A.

It appears that obtaining a reference to a subclass from within a static context is not feasible, so I have resorted to exporting instances of subclasses of A which has proven to be just as effective. Thank you.

Update 2

While there are similarities (the other question does not pertain to subclassing), the reference, even within a static context, is this. Thus, the following code will work:

static foo(){
    this.bar();
}

Answer №1

It seems like you have a grasp on what needs to be done with B.foo(), but I can see your confusion. Are you looking for something like this?

class A {

  static foo(){
    // call subclass static method bar()
    // Because it is "static" you reference it by just calling it via
    // the class w/o instantiating it.
    B.bar() 

  }
}

class B extends A {

  static bar(){
    // do something
    console.log("I am a static method being called")
  }
}

// because "foo" is static you can call it directly off of 
// the class, like you are doing
B.foo()

// or
var D = new B()
D.bar() // won't work ERROR
A.foo() // Works <-- Is this is specifically what you are asking? Or 
        // calling it in the Super class like B.bar(), that is done in static method foo?

If this doesn't address your question, please clarify and I'll do my best to provide an answer. Thank you.

Answer №2

The use of the `super` keyword in the subclass introduces a slight complication to the template pattern, but it allows for the desired functionality. Here's an example:

class A {
  static foo() {
    this.bar()
  }
}

class B extends A {
  static foo() {
    super.foo()
  }
  static bar() {
    console.log("Greetings from B")
  }
}

B.foo()

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 are the steps for creating an electron app using Next.js version 13.4?

Embarking on a fresh project, my aim is to create a desktop application using the powerful duo of Next.js 13.4 and Electron. Surprisingly, I have had difficulty in locating any boilerplates specifically tailored for this combination. Despite experimenting ...

What are the steps to add 8 columns to the second row in my table?

this is an example of HTML code that showcases a table structure with multiple rows and columns. You can view the full code snippet here. The table includes different sections, such as section1, section2, section3, and section4 in the first row (tr). In t ...

Mastering the Art of Writing an Ajax Post Request

I am attempting to transmit an image URL to a node.js server from some JavaScript using the Ajax POST method. My expectation is for the server to respond with some text, but I'm encountering issues and unsure where the problem lies. Below is the relev ...

Is it possible to prevent the late method from running during the execution of Promise.race()?

The following code snippet serves as a simple example. function pause(duration) { return new Promise(function (resolve) { setTimeout(resolve, duration); }).then((e) => { console.log(`Pause for ${duration}ms.`); return dur ...

A guide to filtering out items from observables during processing with RxJS and a time-based timer

I have a complex calculation that involves fetching information from an HTTP endpoint and combining it with input data. The result of this calculation is important for my application and needs to be stored in a variable. async calculation(input: MyInputTy ...

Using a button to dynamically fill a container with data, and then incorporating that data into a function triggered by a click event - JavaScript

Currently, I have a text box where I can enter a letter and click a button to run a JavaScript function. Here is the existing code: <div id="enterlettertext"> Enter the letter:&nbsp; <input type="text" id="myletter ...

What is the process of accessing JSON data transmitted from a Express server in JavaScript?

Working with a node server, I've set up a client-server model, meaning the client connects to "localhost" and express generates a response based on certain logic. While I'm able to send a JSON object through the response, I'm unsure of how t ...

jQuery's AJAX functionality may not always register a successful response

Below is the code snippet I am currently working with: $(".likeBack").on("click", function(){ var user = $(this).attr("user"); var theLikeBack = $(this).closest(".name-area").find(".theLikeBack"); $.a ...

The ajax function threw an error because it couldn't determine the length of an undefined property

When attempting to retrieve the number of objects within an array, I encountered an error stating 'length' of undefined. Here is my JavaScript code: .. success: function(data){ console.log(data.item.length); }, This is my P ...

Generating dynamic slots in VueJS allows for the creation of

Creating slots dynamically from an array is my current task. After some tinkering, I've managed to make it work using the following code snippet: <template v-for="(department,id) in departments" v-slot:[id]="record"> < ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

Handling multiple promises in AngularJS is a common challenge that developers face

I am currently in the process of developing an AngularJS controller that needs to work with multiple promises, each returning a boolean value. The aim is to determine a final boolean value based on these individual results. If all returned values are true, ...

Combining two arrays of objects by their IDs and then categorizing them based on a specific property in

I have a task to merge two arrays of objects (files and counts) based on the "id" property, followed by grouping them by the "folder" property and summing up all counts for each unique "folder". I need to ensure that the final result does not include the " ...

There was an issue with the second level object in the response from the Node.js

Here's the scenario I'm dealing with: app.post('someUrl', function (req, res) { var r = res.data; var a = {}; a.name = r.name || ""; a.someotherKey : { id: r.otherKey.id || "" } }); The issue arises when ...

Is there a way to select a checkbox in Google Forms using the console?

I need help with a script I'm creating to automatically populate Google Forms. I am able to select checkboxes using querySelector, but they don't have a .click() method or similar. How can I go about checking the checkboxes? ...

The proper way to apply the margin-top property in javascript using the DOM style

Struggling to get my div element perfectly centered on the screen. It's aligned in the center, but the top margin stubbornly refuses to budge from the top. I attempted setting divElement.style.marginTop = "100px";, yet saw no change in position. //t ...

ReactJS: The uniqueness of [ this.props ] compared to [ props in this ] is incomprehensible

Inside the componentDidMount method, there is a continuous section of code: console.log('hv props'); for(var i = 0; i<20; i++){ console.log(this); console.log(this.props); } console.log('hv props end'); It is expected that ...

Is there a more optimal approach to preserving color in point material within Three.js while avoiding the detrimental effects of additive blending mode?

Struggling to incorporate a map into a point material with a colored texture in Three.js. Attempted using additive blending and the map attribute to create a rounded point rather than a square one, but it results in the texture color blending with the whit ...

Is there a way to save and display JavaScript outputs simultaneously?

I wanted to create a simple app for myself that can help calculate my pay at work. My pay schedule is every two weeks, and I also get paid based on the kilometers traveled. What I need is that every time I click the "Add" button, the inputs should be displ ...

Having Trouble with JQuery Ajax Syntax?

I've been attempting to make an AJAX request to a server using the Chrome console with the code snippet below: $.ajax({ url: 'http://www.adidas.co.uk/on/demandware.store/Sites-adidas-GB-Site/en_GB/Cart-MiniAddProduct', data: { ...