Do you typically define a static variable within a function using `this.temp`?

I am looking to implement a static variable within a function that meets the following criteria:

  1. It maintains its value across multiple calls to the function
  2. It is only accessible within the scope of that function

Below is a basic example of how I am meeting these requirements:

function func(state, input) {
    switch (state) {
    case 'x':
        this.temp = calc(input);
        return this.temp;
    case 'y':
        return this.temp;
    }
}

While it works, I am curious if there is a more standard or efficient way to achieve this. Any suggestions for improvement would be appreciated.

Answer №1

The specified code does not meet the second criterion. If anything has access to the object referenced by this, it also has access to this.temp. In some cases, this could even refer to the global object, making temp globally accessible everywhere.

To ensure that func stores truly private information, a common approach is to utilize a closure:

const func = (() => {
    let temp;
    return function func(state, input) {
        switch (state) {
            case 'x':
                temp = calc(input);
                return temp;
            case 'y':
                return temp;
        }
    };
})();

This method involves executing an anonymous function to create and assign the func function to the constant, utilizing the closure generated in that process to establish a genuinely private temp variable within func.

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

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

When it comes to using jQuery, I find that it only functions properly when I manually input the code into the Google Chrome console. Otherwise

Below is the HTML snippet: <textarea cols="5" disabled id="textareRSAKeypair"> @Model["keypair"] </textarea> <a href="#" class="btn btn-primary" id="downloadKeypair">Download Key</a> Here is the jQuery code: <script src="ht ...

The element is not defined in the Document Object Model

There are two global properties defined as: htmlContentElement htmlContentContainer These are set in the ngAfterViewInit() method: ngAfterViewInit() { this.htmlContentElement = document.getElementById("messageContent"); this.htmlContentCont ...

Exploring HTML5 video playback in AngularJS

When I use this code: <video id="video" class="video-js vjs-default-skin" controls width="640" height="264"> <source src="http://localhost:3000/files/public/photos/Let-her-go.mp4" type='video/mp4' /> <p class="v ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Encountering difficulties with the functionality of Google Places API

I am attempting to incorporate the autocomplete functionality of Google Places API into a text field. Below is the code I have implemented: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Encountering an unexpected error: receiving a void element tag as input in React

Any ideas on how to resolve the following error message: input is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML` Check out my code snippet below: import "./styles.css"; export default function App() { re ...

[ERROR_HTTP_HEADERS_ALREADY_SENT]: Headers can't be set once they have been sent to the client, expressjs

Whenever I attempt to insert data into my MySQL database using the express router function, I encounter an error. It appears that my server is trying to send a response twice, but I am unsure of where the issue lies. Here is the error message: throw err; / ...

Executing Java method via JavaScript by simply clicking a button

I am currently facing a challenge in finding a way to invoke a Java method from JavaScript and pass user input variables into the method call. The main issue I have encountered is that JavaScript seems to interpret/resolve the Java method during page load. ...

Preventing the display of AngularJS HTML tags while the app is being loaded

I am new to AngularJS (using version 1.5.8) and I am currently following the tutorials provided on docs.angularjs.org/tutorial. Below is the HTML code snippet: <div class="jumbotron"> <h1>{{application_name | uppercase }}</h1> ...

Removing background color and opacity with JavaScript

Is there a way to eliminate the background-color and opacity attributes using JavaScript exclusively (without relying on jQuery)? I attempted the following: document.getElementById('darkOverlay').style.removeProperty("background-color"); docume ...

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api') When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so: (method) AxiosInstance.get<any, AxiosResponse<any> ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...

Tips for incorporating a visible marker beside the dropdown arrow

When developing my React application with React hooks forms, I have a select component where I need to include a clear indicator 'x' icon next to the dropdown icon. The current select component code is: <Form.Control size="sm" as=&q ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

When I attempt to navigate using a route on my website, all I see is a

Hey everyone, I'm looking to develop a webpage that switches pages using Navbars. I want to utilize bootstrap and react-route-dom to achieve this functionality. However, before incorporating bootstrap, I encountered some errors that went unnoticed. I& ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...