Identifying static super method within an ES6 class

My goal is to have a base class and a subclass with class types that each have a static method identifying them using a string. This will enable me to easily look up handlers for different types in an object. I initially tried storing the class directly in the object, but converting the entire source of the class to a string and using that as a key did not seem like the most efficient solution.

Here are my requirements:

  • Detect if a superclass is present
    • Call `super.id()` then append my own `id()`
  • If there is no super class, just use my own `id()`

I attempted to write the code in this way, but encountered issues because `super.id` is undefined. Checking for `if (super) {}` resulted in a syntax error, and calling `super.id()` returned "not a function".

class Y {
  static id() {
    if (super.id) {
      return `${super.id()}-${this.name}`;
    }
    else {
      return this.name;
    }
  }
}

class YY extends Y {}

// Currently outputs "Y YY", but desired output is "Y Y-YY"
console.log(Y.id(), YY.id()) 

I could define a `static id() {}` method in `YY`, but this would require manually implementing it in all subclasses, which can lead to errors. Is there a way to achieve this more efficiently?

Answer №1

Instead of using super, you can utilize Object.getPrototypeOf:

class Y {
  static id() {
    if (Object.getPrototypeOf(this).id) {
      return `${Object.getPrototypeOf(this).id()}-${this.name}`;
    }
    else {
      return this.name;
    }
  }
}

class YY extends Y {}

console.log(Y.id(), YY.id()) 

Using super may not work as expected, as it always refers to the prototype of the Y class. However, utilizing this accurately matches the object that requires the prototype of. Therefore, by using Object.getPrototypeOf(this).id, you can effectively traverse through the prototype chain.

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

finding the initial element within an object using lodash in javascript

Recently, I came across some data in the form of an array of objects. For instance, let me share a sample dataset with you: "data": [ { "name": "name", "mockupImages": "http://test.com/image1.png,http://test.com/image2.png" }] ========================== ...

What is preferable: defining JSON schema properties or utilizing oneOf conditions within an array of objects

I am looking to represent a variety of objects in a schema through an array called contents. This array can include any number of elements, but they must fall into one of two categories: one type represents text while the other type represents images. Up ...

Integrate a loading screen on the website

Check out the awesome animation I created! Can this be used as a preloader on my website? Should I stick to creating a simple .gif or opt for a CSS animation instead? If it’s feasible, how do I go about integrating it into my site? Most tutorials suggest ...

Is it possible to establish a default URL for the expect() function?

One of the challenges I'm facing is with my Restangular call, which has a baseUrl configured in a specific file as http://localhost:3000/. For example, a call like: Restangular.all("awards").customPOST(award) Actually makes a request to baseUrl+"awa ...

Manage and oversee Leaflet GeoJSON layers within a variable or object while incorporating incremental adjustments

As I explore this question, my goal is to store geoJson layers in a variable using a javascript loop and then utilize them on my map with a layer control panel. Take a look at the following code: myURL = [ "http://localhost:8080/geoserver/jonquiere_lo ...

How can you check the status of a message sent using Stompjs?

I have been working on a chat application using Spring Boot Websocket, STOMP, and stompjs. Below is a snippet of my JavaScript code: <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.1.4/sockjs.min.js"></script> < ...

Moving the mouse cursor to the middle of a child div with the use of the mousemove event

I am currently facing an issue with positioning a div inside another div using jQuery's mousemove event. Despite setting the CSS attributes inline with jQuery ('top': relY + 30, 'left': relX + 10), I am unable to get the cursor in ...

Anticipating the issue: Strategies for minimizing nested callback functions in Node.js with Express

Recently I have been delving into the world of node.js, specifically using Express to create a basic website integrated with a MySql database. I've followed the standard application structure provided by Express (which is not relevant to my query). I ...

Best Practices for Implementing AngularJS Dependency Injection

I am excited to share that I have recently started delving into my very first Angular JS project. As I navigate through this new experience, I want to ensure that I am effectively managing Multiple dependency injection. Any insights, recommendations, or ...

Fresh class retains the characteristics of the former class

As I navigate my way through learning jQuery, I've encountered a puzzling issue that I can't seem to solve. No existing articles seem to address my specific problem, so I am turning to this platform in hopes of finding a solution. I'm puzz ...

Retrieving an image from an input file and setting it as the background of a div element

I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful. HTML: <inpu ...

Error encountered during login with Facebook on Cordova: "Unable to create module facebookApp because of..."

As a novice programmer, I am attempting to incorporate Facebook login using Cordova. Following a recent guide provided here, I have meticulously copied and pasted the code into a new Cordova project. While I am familiar with jQuery, this is my first encoun ...

Displaying content generated by Html.Raw in MVC4 using JavaScript and AJAX is causing displacement of content within the <a> tags in the HTML

My project includes a feature where emails sent to a specific address are parsed, with attachments saved to the network and metadata stored in a database. If the serial number of a finished good matches the one included in the email, a note is generated an ...

Encountered an error when attempting to extend the array function: Uncaught TypeError - Object [object Array] does not contain a 'max' method

Hello, I am currently attempting to integrate this function into my code: Array.getMaximum = function (array) { return Math.max.apply(Math, array); }; Array.getMinimum = function (array) { return Math.min.apply(Math, array); }; This is inspired ...

There was an error: Unable to access the 'filter' property of an undefined variable

import React, {PureComponent} from 'react'; import {TextInput} from '../../shared'; import {array} from 'prop-types'; import { EmployeeTable } from '../employeeTable/EmployeeTable'; import './HeaderSearch.scss&a ...

Tips for enabling both vertical and horizontal scrolling using the mousewheel on a webpage

Our website features a unique scrolling functionality where it starts off vertically and then switches to horizontal once the user reaches the bottom. This allows for a seamless transition between scrolling directions. In addition, users can easily naviga ...

A method for applying the "active" class to the parent element when a child button is clicked, and toggling the "active" class if the button is clicked again

This code is functioning properly with just one small request I have. HTML: <div class="item" ng-repeat="cell in [0,1,2]" data-ng-class="{active:index=='{{$index}}'}"> <button data-ng-click="activate('{{$index}}')">Act ...

Convert a JSON array with a single element into a valid JavaScript object

Within my programming scripts, I frequently utilize PHP arrays with numeric keys. However, these keys are not necessarily sequential from 0 to n; they can be randomly chosen. Specifically, I am working on a script that organizes scheduled events at specifi ...

Use jQuery to dynamically add a button to a table row

I have an array of JSON objects in JavaScript that I'm parsing from a JSON formatted string. My current approach involves looping through the array and adding the data to a table on the page. jQuery Code: $.each(objArr, function(key, value) { var ...

Using JavaScript to Implement a Scrolling List

Currently, I am diving into the world of coding with HTML, JavaScript, and CSS for a college project. Unfortunately, my instructors aren't providing any assistance, so I'm turning to you for help. I have managed to put together some code to crea ...