Stay dry - Invoke the class method if there is no instance available, otherwise execute the instance method

Situation

When the input is identified as a "start", the program will automatically calculate the corresponding "end" value and update the page with it. If the input is an "end", simply display this value on the page without any modifications.

I am in the process of creating a custom class to manage this task efficiently.

class EndVal(start_value) {
  constructor() {
    this.end_value = start_value + 10
    $("#end").text(this.end_value)
  }

  static prefill(end_value) {
    $("#end").text(end_value)
  }
}

The code provided above allows you to handle "start" inputs by utilizing new EndVal(start_value), while for "end" values, you can directly use EndVal.prefill(end_value). However, I find this approach slightly repetitive. Is there a way to streamline it and establish a connection between instance and class methods?

Answer №1

The prefill function should utilize the provided argument instead of referencing this. This enables calling the method directly from the constructor:

class EndVal {
  constructor(start_value) {
    this.end_value = start_value + 10
    EndVal.prefill(this.end_value);
  }

  static prefill(end_value) {
    console.log(end_value);
  }
}

const endVal = new EndVal(15);

EndVal.prefill(28);

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

Sending Data via Ajax

I am currently working on implementing an ajax invitation script that allows users to invite their friends to an event. The javascript code I have used in other parts of the website works perfectly, but for some reason, it is not functioning correctly in t ...

Choose each day's time slot on the jQuery FullCalendar version 2.x

The code snippet below is a segment of the code generated by the FullCalendar jQuery plugin version 2. It has undergone some changes from version 1.x in terms of the classes it utilizes. <div class="fc-slats"> <table> <tbody> ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

"Method to change the value in a form input field from a specific

On my profile page, the admin can edit user profiles in a single process. How can I automatically refresh and update the form data after a successful query update? class User { ... public function updateUser($id, $firstname, $lastname, $phone, $birth ...

What's preventing me from tapping on hyperlinks on my mobile device?

I'm currently working on a website (saulesinterjerai.lt) and everything seems to be functioning properly, except for the fact that on mobile devices, the links aren't clickable and instead navigates to other layers. How can I disable this behavio ...

When encountering error code EINTEGRITY during npm installation, a warning about a potentially corrupted tarball may be displayed

I have been facing an issue for the last three days with my react+vite project on Windows 10. Whenever I attempt to install dependencies using npm install, I encounter the following error: npm WARN tarball tarball data for fast-levenshtein@https://registry ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Preventing Click Events from Firing During Drag in JavaScript

I have implemented a code for dragging containers left or right, which is functioning properly. Users can also click on the "thumb". However, I am facing an issue where a click event occurs even after dragging. I want to ensure that only either drag or cli ...

Incorporating External JavaScript and CSS specifically for a single component

In my Angular 4 application, I have a specific component that requires the use of a js and css file. While most guidelines suggest placing these files in the Index.html file, I prefer to only load them when this particular component is accessed, not on e ...

Exploring the process of sending post data and navigating to a URL using AngularJS

I am working on an application using angularjs 1.6 and Java 8. My goal is to send POST data to another application and navigate to the URL that this external application determines. The purpose of my application is to transmit data about a citizen who wan ...

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

The constructor error in ng-serve signalizes an issue in

Currently, I am developing an AngularJS application. However, when attempting to start the dev server, I encountered an issue with my ng serve command: https://i.stack.imgur.com/QujSe.png ...

ReactJS form submissions failing to detect empty input values

My goal is to use react to console.log the input value. Below is the code I've created: import React from 'react'; import ReactDOM from 'react-dom'; class App extends React.Component{ constructor() { super(); this.proce ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

Caution: It is important for every child in a list to have a distinctive "key" prop value. How can a shared key be used for multiple items?

When I click on a header from my list, an image should appear. However, I'm encountering an error that needs to be resolved. I've been struggling to find a solution for adding unique keys to multiple elements in order to eliminate the error. Des ...

Activate Bootstrap datetimepicker by using the enter key to automatically populate the initial date

Check out the Bootstrap datetimepicker on this page: I'm trying to make it so that when the datetimepicker is first shown, pressing the enter key will hide the widget and insert the current date into the input field. I've experimented with a few ...

What could be the reason for webpack not making jQuery available as a global variable?

For my current project, I am utilizing several npm modules by integrating them using yarn and webpack. These essential modules include jquery, bootstrap3, moment, jquery-tablesort, jquery-ujs, bootstrap-select, and livestamp. Some of these plugins require ...

Show the current temperature data retrieved from the weather API

I'm trying to figure out what's causing the issue with the temperature not displaying. Can anyone help me identify and fix the error? <script type="text/javascript"> $.ajax({ url: 'https://api.weather.gov/gridpoints/EWX ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

Tips on saving additional parameters in an API URL with AngularJS

Here is my AngularJS function code: $scope.cardcall = function (cardtype) { $scope.cityname=cityname; $http({method: 'GET',url: '/api/v1/asasas&filterBy=cardNames&filterByValue='+cardtype.key}).success(funct ...