Static variable storing instances of objects

I am faced with the following scenario:

function Configuration() {
}
Configuration.users = {
  'user1': new User()
}

The users variable is a static member of Configuration and I am attempting to have it store an instance of a User object. However, I am encountering some difficulty with this approach. It seems that I am able to define users as a non-static member variable instead. Like this:

function Configuration() {
  var users = {
    'user1' : new User()
  }
}

Is there a way to create a static member variable that can hold instances of an object in JavaScript?

Answer №1

If you want to achieve this, there are a few different methods you can use. One approach is to directly implement it within the function:

var foo = function() {
    if ( typeof foo.static == "undefined" ) {
        foo.static = Math.random();
    }
};

console.log(foo.static);
foo();
console.log(foo.static);
foo();
console.log(foo.static);

Result:

undefined
0.33120023757048356
0.33120023757048356

Alternatively, you can utilize a prototype in a constructor function as shown by Iggy Kay.

Another way is to simulate static variables using an anonymous function to create a closure:

var Foo = (function() {
    var static = {x: Math.random(), etc:3};

    // Instantiable object
    return function() {
        this.a = Math.random();

        this.bar = function() {
            console.log(this.a, static);
        };
    };
})();

var f1 = new Foo(), f2 = new Foo(), f3 = new Foo();
f1.bar();
f2.bar();
f3.bar();

Result:

0.318481237168568   Object { x=0.35319106907436637, more...}
0.5422140103705965  Object { x=0.35319106907436637, more...}
0.30933348253602777 Object { x=0.35319106907436637, more...}

Or you can follow the same concept but with the module pattern:

var Foo = (function() {
    var static = {x: Math.random(), etc:3};

    // Module pattern
    return function() {
        return {
            a: Math.random(),
            bar: function() {
                console.log(this.a, static);
            }
        };
    };
})();

var f1 = new Foo(), f2 = new Foo(), f3 = new Foo();
f1.bar();
f2.bar();
f3.bar();

Result:

0.2368968219817239 Object {  x=0.17619776914569862,  more...}
0.5411810225426568 Object { x=0.17619776914569862, more...}
0.3319039598508573 Object { x=0.17619776914569862, more...}

Answer №2

To ensure that multiple instances of Preferences can share the static list of players, you can define them in the prototype like this:

function Preferences(){}
Preferences.prototype.Players = {'player1': new Player() }; 

var pref1 = new Preferences();
alert(pref1.Players.player1); 

var pref2 = new Preferences();
alert(pref2.Players.player1); 

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

Running a Node JS application concurrently with an Express API connected to MongoDB

Here's my current project plan: I've created a small Node app that fetches data about the stock market from an API and then stores the data in a Mongo DB (which is already up and running). My next step is to create an API that will allow other se ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...

I aim to retrieve the names of all directories

I am seeking assistance from seniors in creating a dropdown list of root directories using PHP. I have almost completed the task, but I am facing an issue with not being able to retrieve the root directory. For example, I want all directories like home/ab ...

What is the best way to modify an array of objects within component state?

I am currently working on updating a specific property of an object that is stored in an array. Here's a glimpse of my current state: state = { todos: [ { id: '1', title: 'first item, completed: false }, { ...

Receiving a console notification about a source map error

Recently, I started receiving this warning in my console: "Source map error: request failed with status 404" resource URL: map resource URL: shvl.es.js.map" Has anyone encountered this issue before? I'm unsure of what it might be? This is my webpa ...

The sorting feature is not performing as anticipated

I'm dealing with an array of objects fetched from the backend. When mapping and sorting the data in ascending and descending order upon clicking a button, I encountered some issues with the onSort function. The problem lies in the handling of uppercas ...

The expiry date of the cookie remains unchanged

When attempting to create a cookie and specify an expiration date, I am encountering an issue where it remains as "Session". This problem is occurring in Google Chrome. I'm looking for insights on what might be causing this behavior. The code snippe ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Update the variable obtained from the user input and insert it into a new container depending on the input value

In reference to my previous inquiries, I refrain from adding more details to avoid confusion since it already received numerous responses. While I can successfully retrieve input from a text field with the ID 'test' and display it in the 'r ...

Choose the tag and class then retrieve the custom attribute

I'm currently attempting to retrieve a specialized attribute utilizing jquery and subsequently choose it, nevertheless I am encountering some difficulties with the process Below is the jquery code I have implemented to access the value var stockId = ...

Submitting form data using Vue and PHPMailer

I've been encountering an issue with submitting a contact form from a page. After submitting the form, nothing seems to happen. My tech stack includes Vue, Axios, and PHPMailer for handling this functionality. Upon inspecting the network tab, it appea ...

There are multiple sets of radio buttons within nested ng-repeats, but only the final group displays the selected value

I am having an issue with updating a form that contains multiple radio buttons based on data retrieved from an API. The challenge is that only the last set of radio buttons displays the value correctly. Below is the code snippet I am using (angular bracket ...

JavaScript - Error encountered when accessing information from elements in the DOM

Just started learning javascript and encountering a problem that I can't seem to solve. I'm attempting to assign the className of a <div> element to a variable, but I keep receiving this error message: scripts.js:30 Uncaught TypeError: Can ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have: $scope.Reports = [ { Id: 1, Name: 'Report One', Year: 2016, Month: 5 }, { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 }, { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 }, { I ...

The process of compressing font files (such as ArialMT.ttf) using JSZip is experiencing issues

While zipping images and HTML files works smoothly, I encountered an issue when trying to add font files for CSS. The font file is only 1kb in size, but it cannot be opened. Even after attempting to zip the font without any other files, the problem persis ...

Direct users from one path to another in Express framework

I have two main routes set up in nodejs. First is the users.js route: router.post('/users/login', function(request, response) { // Logic for user login // Redirect to dashboard in dashboard.js file after login response.redirect(&ap ...

Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format. One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted t ...