Is it possible to create a "private" variable by utilizing prototype in JavaScript?

In my JavaScript code, I am trying to have a unique private variable for each "instance," but it seems that both instances end up using the same private variable.

func = function(myName)
{
    this.name = myName
    secret = myName

    func.prototype.tellSecret = function()
    {   return "the secret of "+this.name+" is "+secret
    }
}

f1 = new func("f_One")
f3 = new func("f_3")

console.log(f3.tellSecret()) // "the secret of f_3 is f_3" OK
console.log(f1.tellSecret()) // "the secret of f_One is f_3" (not OK for me)

I came across a possible solution, but

this would mean duplicating the function on every instance, and the function lives on the instance, not on the prototype.

Another developer mentioned a similar solution in this post

That's still not quite traditional class-based JavaScript, which would define the methods only once on Account.prototype.

So, I'm wondering if there is a way to achieve:

  • have every instance with unique values for secret
  • ensure that secret is only accessible to methods defined in the constructor, and
  • avoid duplicating functions for each instance

Is there a solution for this?

Answer №1

The issue lies in the fact that each time the constructor is called, you are replacing your prototype function.

When using old-style closure-based privacy, accessing "private" members from prototype methods is not possible because only functions defined in the constructor closing over them can utilize them. This results in recreating the functions for each instance, which may not be as detrimental as it sounds but is not an ideal approach.

function Example(name) {
    this.name = name;
    var secret = name; // Using `var` here assuming ES5-level code

    // Unable to be a prototype function
    this.tellSecret = function() {
        return "the secret of " + this.name + " is " + secret;
    };
}

You have two alternatives:

1) Utilize a transpiler like Babel, class syntax, and private fields (anticipated to be available in ES2021, currently used by transpiling):

class Example {
    #secret;

    constructor(name) {
        this.name = name;
        this.#secret = name;
    }

    tellSecret() {
        return "the secret of " + this.name + " is " + this.#secret;
    }
}

const f1 = new Example("f_One");
const f3 = new Example("f_3");

console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
console.log(f1.tellSecret()) // "the secret of f_One is f_One"

2) Employ a WeakMap (ES2015+) containing the confidential information:

const secrets = new WeakMap();
class Example {
    constructor(name) {
        this.name = name;
        secrets.set(this, name);
    }

    tellSecret() {
        return "the secret of " + this.name + " is " + secrets.get(this);
    }
}

const f1 = new Example("f_One");
const f3 = new Example("f_3");

console.log(f3.tellSecret()) // "the secret of f_3 is f_3"
console.log(f1.tellSecret()) // "the secret of f_One is f_One"

secrets should be placed where only Example can access it.

You can also use a WeakMap without employing class syntax, but when constructing functions with associated prototypes, using class is more straightforward than defining function Example and assigning properties on Example.prototype.

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

Completing the regex properly

When using my editor, I am able to paste a video URL which is then converted by regex into an embed code. The URL in the WYSIWYG-editor looks like this: Once converted, the output HTML appears as: <p>http://emedia.is.ed.ac.uk:8080/JW/wsconfig.xml& ...

Learning how to integrate Next.js, React.js, and Redux into an HTML page for an enhanced user

My current project is built on Asp.Net MVC, but the technology used is not crucial. I integrated react.js and redux for searching a section of my html page using a cdn link. Now, I am considering deploying the server side of the application with next.js. ...

The touchstart event handler triggers but the event returns as undefined

@ontouchdown="handleTouch(event)" handleTouch(event) { console.log(event); console.log("touch event"); } Why is the event not being passed properly? ...

`Adjusting function calls based on the specific situation`

On my webpage, I have implemented a tab system where clicking on a tab displays the corresponding content below. This functionality is controlled by a JavaScript/jQuery function called 'changeTab'. Now, I want to set up individual JavaScript fun ...

Interactive Content Swapping: How to Use Javascript for Dynamic Link Updates

http://jsfiddle.net/bUjx7/42/ <script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.js'> </script> <script type='text/javascript'> $(document).ready(function () { $('.fieldreplace ...

Automatically updating div content using a static HTML page

Is there a way to refresh the content of an HTML div tag every 5 minutes without having to reload the entire page? <div id="pie"> <script src="index.js">// this script should be reloaded every 5 minutes </script& ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

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 = ...

Verify if there are duplicate values present in a table

I have a Table that contains multiple rows, each row having input fields. I need to check for duplicate values within the table. Below is my code where I am currently checking for empty values, how can I modify it to also detect duplicate values? JavaScr ...

Sending an object to a Vue 2 component and confirming its validity

I am working with a Vue component that has numerous props. <Field v-for="field in fields" :key="field.name" :name="field.name" :type="field.type" :label="field.label" :values="field.values" :value ...

Failure to display alert message upon completion of AJAX request

I am attempting to use AJAX to send data to the database without refreshing the page when a user favorites a message. Even though the data is successfully sent to the DB, the page still reloads and the alert message I want to display is not showing up. Th ...

I am consistently encountering the error message: "Error: Unable to locate module './framer'"

I've been running into the same issue repeatedly. I'm in the process of creating a website for a barbershop and I'm attempting to integrate events into a Google calendar using the Google API. I've installed googleapis and framer, but I ...

Receiving the result as well as encountering undefined initially during AJAX request

I have a dropdown menu, and when a user selects an option, an AJAX call is made to retrieve and display data based on the selected value. If the dropdown value is 2, it triggers the AJAX request. However, I am encountering two issues: https://i.sstatic.n ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

What is the best way to create a form that includes both dynamic objects and dynamic arrays using a JSON schema?

I have observed how a JSON schema can be utilized to construct dynamic arrays. My goal is to develop a JSON web form using a JSON schema that allows for objects (dictionaries) to be expandable similar to arrays. For example, you can visit the demonstrati ...

The JavaScript code is executing before the SPFX Web Part has finished loading on the SharePoint page

I recently set up a Sharepoint Page with a custom masterpage, where I deployed my SPFx Webpart that requires certain javascript files. While the Webpart functions correctly at times, there are instances when it doesn't work due to the javascript bein ...

Ways to display a default view in React

I am working on a React website that has three different routes. My goal is to have the first route, named Home, automatically displayed when a user lands on the site. Below is the code snippet from my App.js: <Router> <Navigation /> <Sw ...

Adding Labels to Doughnut Charts in React using Chart.js 2.0

Currently, I'm exploring the world of data visualizations using react, react-chartjs-2, and chart.js version 2.2.1. While searching for a solution to my inquiry, I came across a potentially relevant answer on this link (specifically check out the upda ...

Trouble with tab switching across multiple cards

I have been working on an app that generates multiple cards with 3 tabs on each card. However, I am facing an issue with tab switching. The tab switching works fine on the first card, but when I try to switch tabs on other cards, it still affects the tabs ...

Trigger a refresh of the Angular app by clicking a button

Recently, I embarked on developing a single-page application that allows users to input data in a text box and navigate to another page. While designing the second page, I aimed to incorporate a home button that would not only return me to the initial view ...