Setting the property of an object member using an array member within a JavaScript singleton

My JavaScript code includes a "singleton" class like this:

ExpressionValidator =
{
    // A map of function names to the enumerated values that can be passed to it.
    functionParamValues:
    {
        "Func1": ["value1", "value2", "value3"],
        "Func2": ["value1", "value2", "value3"]
    }
}

I'm looking for a way to define the array ["value1", "value2", "value3"] in a more efficient manner, rather than duplicating it. However, I am struggling to make it work.

One approach I have tried is:

ExpressionValidator =
{
    // An array of possible values to use as parameters to certain functions.
    values:
    [
        "value1",
        "value2",
        "value3"
    ],


    // A map of function names to the enumerated values that can be passed to it.
    functionParamValues:
    {
        "Func1": values,
        "Func2": values
    }
}

Unfortunately, this solution doesn't work because it cannot find the values array when initializing the "Func1" and "Func2" properties within the functionParamValues object. I also attempted using this.values instead of just values, but it returns null, indicating that it's trying to access the values property of the functionParamValues object rather than its parent ExpressionValidator.

I understand that I could resolve this issue by moving the values array outside of the ExpressionValidator definition, but I prefer to keep it contained within if feasible to avoid conflicts with the global namespace. This should be considered only as a last resort if no other alternatives are available.

Answer №1

To prevent a variable from being in the global scope, enclose it within a closure.

var ArrayEncryptor = (function() {
    var encryptedArray = [ 
        'encrypt1',
        'encrypt2',
        'encrypt3'
    ];       

    return {
        securedArray: encryptedArray,
        functionValues: {
            FuncA: encryptedArray,
            FuncB: encryptedArray
        }
    };
})();

Answer №2

When you write a literal like that without any function scope to set the value this, wrapping everything in IIFE's will be necessary to access the values.
A more effective pattern for achieving your desired outcome would be as follows:

var DataValidator = {};

DataValidator.values = [
    "item1",
    "item2",
    "item3"
];

DataValidator.functionParamValues = {
    Function1: DataValidator.values,
    Function2: DataValidator.values
}

FIDDLE

If there were actual functions involved, the approach would differ slightly

var DataValidator = {
    values: [
        "item1",
        "item2",
        "item3"
    ],
    Function1: function() {
        console.log( this.values );
    },
    Function2: function() {
        console.log( this.values );
    }
}

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

ReactJS encountered an error: _this3.onDismissID is not defined as a function

My goal is to retrieve the latest news related to a specific search term from a website, showcase them, and provide a dismiss button next to each news item for users to easily remove them if desired. Here's a snippet of the code I'm using: import ...

What could be the reason why this LESS CSS is not taking effect?

Why won't this stylesheet load properly? The desired background color is supposed to be similar to cadetblue. You can view my page with the linked home.less.css at: ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

What is the best way to trigger a modal to appear when dynamically generated items are clicked?

My objective is to retrieve specific data from the server and present it in a list format on my webpage. The list displays correctly, but I want users to be able to view additional details for each list item by clicking on it, triggering a modal popup. How ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

Can you explain the reference point used in the `drawImage()` function on a canvas?

Here is an inquiry concerning the usage of the drawImage() function. var x = (i-j)*(img[0].height/2) + (ctx.canvas.width/2)-(img[0].width/2); var y = (i+j)*(img[0].height/4); abposx = x + offset_x; abposy = y + offset_y; ctx.drawImage ...

A useful tip for jQuery users: learn how to prevent the context menu from appearing when a text box is

Is there a way to prevent the context menu from appearing in jQuery when the text box is disabled? The right-click disable functionality works well in all browsers except for Firefox. Please note that the right-click disable functionality works when the t ...

Dealing with CORS, IIS7, and PHP - Overcoming the Access-Control-Allow-Origin obstacle

I am attempting to enable another local host (such as javascript.dev) to make a xhr request to this particular host, which operates on an IIS7 server. When I perform a curl -I command, the headers I receive are as follows: HTTP/1.1 200 OK Content-Length: ...

The Javascript function must be executed with each page reload

Currently, I am analyzing an asp.net 2 web application that is in my care (even though I did not create it). There seems to be an issue with certain functionalities not working consistently when the page loads, particularly if using Firefox 3 within a vir ...

Node.JS function using try catch block

Is the following function suitable for use with Async Node.JS? I am wondering if it is written correctly, whether errors will be handled properly, or if it has been incorrectly implemented in terms of Async Node.JS. If there are issues with the implemen ...

Is it possible to install in a directory other than the one specified in package.json

I have organized my folders exactly how I want them to be. In one specific folder, all of my configuration files reside (most importantly package.json). I am looking to install this package.json configuration in a different path, specifically c\instal ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Error 404: Unable to locate webpack bundle.js

As I dive into learning about Webpack configuration, I keep encountering errors in my console. It appears that my webpack app.bundle.js file is not being found. The page successfully loads with the content of my HTML file displaying, but the app.bundle.js ...

What is the best way to fetch Ajax information for use in several drop-down menus?

Is there a way to populate one multiple select drop-down based on the selection made in another multiple select drop-down using jQuery or ajax? Here is an example of how I am attempting to achieve this using ajax: function demo1() { var emp_id = docu ...

How can I use JQuery to iterate through Object data and dynamically create tr and td elements?

In previous projects, I utilized Vanilla JS to iterate through Ajax return data and construct tables. However, for this current project, I have decided to switch over to JQuery. The main reason behind this decision is that some of the td elements require s ...

Show the elements of an array (that have been read and processed from a text file) on separate lines using JavaScript

Hello, I have the code below where a user can upload a text file. I attempted to display the output in a div after splitting it using the @ character. The array elements stored in variables are correctly displayed with new lines in an alert, but they are p ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Why isn't the field I added to my state functioning properly?

Can anyone explain why I am getting names without the added selected field??? I can fetch names from my API JSON (1) and I'm attempting to modify it by adding the selected field (2). export default function Display() { ... const init ...

When a block is clicked, jQuery will reveal that block while hiding the others sequentially, starting with the second block, then the third, and finally the fourth

Creating a navigation menu with 4 blocks can be a bit tricky, especially when trying to show one block at a time upon click. Here is my code attempt, but unfortunately it's not working as expected. I would greatly appreciate any help or suggestions on ...