Securing the variables by making them private and retrieving them through a shared function in JavaScript

I am looking to create an Object that will encompass all the immutable properties which cannot be altered from outside sources,

for instance :

var Constants = (function(){
    this.server_port = 8888;
    this.server_name = '127.0.0.1';

    return ({
            getConstantValue : function(constantName){
                /*
                  This function will retrieve the property based on the 
                  name of the constant provided
                */
            }
    });
}());

Therefore, if anyone were to input

Constants.getConstantValue('server_port');//will yield 8888;
Constants.getConstantValue('server_name');//will yield 127.0.0.1;

How can this be accomplished without exposing the properties externally? I would appreciate any insight or suggestions. Thank you in advance.

Answer №1

Discover the Power of Closures! Take a look at this simplified version:

var constants = (function() {
    var constList = {
        server_port : 8888,
        server_name : '127.0.0.1'
    };
    return ({
        getConstantValue : function(constantName) {
            return constList[constantName];
        }
    });
}());

Answer №2

An alternative approach would be to utilize actual properties in a more organic manner, like this:

function Constants(obj) {
    var o = {};
    Object.keys(obj).forEach(function(key) {
        o.__defineGetter__(key, function() { return obj[key] })
    });
    return o;
}

or

function Constants(obj) {
    var o = {};
    Object.keys(obj).forEach(function(key) {
        o[key] = { writable: false, value: obj[key] }
    });
    return Object.create({}, o);
}

Following that, you can use it as follows:

configuration = new Constants({
    'server_port': 8888,
    'server_name': '127.0.0.1'
})


console.log(configuration.server_name) // Outputs: 127.0.0.1
configuration.server_name = 'blah'
console.log(configuration.server_name) // Still returns: 127.0.0.1

Answer №3

Here is a useful resource you can check out for further reference: (demo):

var Constants = (function(){
    var server_port = 8888;
    var server_name = '127.0.0.1';

    return ({
            getConstantValue : function(constantName){
                if(constantName == "server_port")
                {
                    return server_port;
                }
            }
    });
}());

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

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

How can client-side routing be effectively utilized?

I have a question about the utilization of AngularJS and Node.js in my web application. I have implemented client-side routing using routeProvider to navigate within different pages. All data is retrieved from a RESTful API server-side. However, most of ...

AngularJS is throwing an error stating that the URL ID is undefined

I am developing an application that utilizes angularjs with codeigniter as the backend. Within my URL, I have http://localhost/submit/1234, with 1234 serving as the ID. Within my angularjs setup: var singlepost = angular.module('singlepost', [ ...

Utilize Vus.js 2.0 in conjunction with Laravel 5.4 to pass an object to the application and allow for its global usage

How can I efficiently load the authenticated user and access it across all my Vue components without making unnecessary AJAX requests, as I can directly fetch it from the back-end? In my Laravel home.blade.php file, I have a reference to a Vue app and att ...

Utilize Java with AJAX to store form information in a MySQL database through Rest Web Services

I am currently facing an issue while trying to add a record to my MySQL database using an HTML form. I have implemented AJAX to call Java web services, but for some reason, it's not functioning as expected. The system displays an alert with the messag ...

The onchange event is failing to trigger any JavaScript function

I am facing an issue where the onchange event of a dropdown menu is not triggering at all. I even tried redirecting it to a simple JavaScript function for testing purposes, but that didn't work either. I'm struggling to find a solution. Below is ...

Utilizing React, Graphql, and Next.js, you can expect to receive an object or JSON value instead of the

Presently, I am viewing an object output of {value=1, label=USA} https://i.sstatic.net/MLeIT.png However, I would like to only access the label output USA on my-post page On the create-post page, I am able to access post.countries ? countries.label : &qu ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Transform Json data into CSV file format with customized headers and formatting

I have a function in my code that fetches JSON data from an endpoint and converts it into a CSV file. Is there a way for me to specify specific headers and the order of columns I want in this CSV file? function downloadJSONAsCSV(endpoint) { // Fetch J ...

When saving, Vue sporadically creates misleading error messages

Recently, I started a new Vue project that wasn't very populated. When I run the command below, everything runs smoothly... npm run serve However, as soon as I make a small change in my project and hit CTRL+S, the Vue instance is rebuilt and strange ...

Tips for escaping an infinite loop within the componentDidUpdate function in reactjs

Currently, I am working on creating dashboards using reactjs. I have successfully implemented 4 tabs or buttons for charts, but I am facing an issue when clicking on different dashboards that have the same chart in the same panel. The chart is not updating ...

Setting up Identity Server 4 integration with Ionic 2

Currently, I am in the process of setting up Identity Server to function with Ionic 2. I am a little confused about how to set up the Redirect URLs specifically for testing purposes in the browser. Furthermore, I am updating and integrating an OIDC Cordov ...

Is the Date Epoch a reliable form of unique identification?

Currently, I'm developing a Node API and encountered a situation where I need to create a unique 15-digit random number for a model without using autoincrement. The challenge is to ensure that the generated number is not trivial. I am hesitant about ...

Generating a JSON object from a Java List containing nested lists

I have a set of nested lists that I need to convert into JSON format. The structure of the list is as follows: [Country, Food, Detail, Population, Region, Extension] [Germany, 1, 2, 3, 4, 5] [England, 10, 11, 12, 13, 14] [USA, 19, 20, 21, 22, 23] [China, 2 ...

Utilize the v-model directive for dynamic searching within a v-for rendered array in Vue.js

I haven't used Vue.js in a while. I am currently working on a simple app where I'm rendering items using a v-for from an array. I want to implement an input box with a v-model to search through the list of items (presets). Code <div class="r ...

Is it feasible to utilize a variable as a function within JavaScript programming?

I've been diving into the world of express.js and came across these statements. const express = require('express'); const app = express(); It's intriguing how we can call the variable "express" as a function by simply adding parenthese ...

What is the proper way to declare an empty timestamp variable as a global variable so that we can assign a value to it later on?

How can I declare a global timestamp variable with an initial empty value that I can use within my functions and assign values to as needed? For instance, if I have two buttons that each trigger a method: <button (click)="startTime()">Starting time ...

The conversion of an org.json.JSONObject type to a JSONArray within an Android JSONObject is not possible

I am currently working on extracting data from a JSONObject that includes an array of user details. My current task involves retrieving the username from this json object. If you would like to view the JSON data, please click here. So far, I have succes ...

Begin the initial function again once the second function has been completed

I have 2 functions in my code: function DisplayAltText(){ var CurrentPhoto = $("#DisplayPhoto img").attr("src"); if( $.browser.msie ) { IECurrentPhoto (CurrentPhoto); } if ($(".PhotoGallery img[src='" +CurrentPhoto+ "&a ...

Is it possible for me to customize the default angular filter in order to prioritize displaying strings that begin with the search term?

In my current project, we are dealing with a massive list of strings (17,000+ at times) and have implemented an input box for filtering the list. Initially, I used Angular's default filter, but then a request came in to sort the list so that strings s ...