Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Revealing Prototype Pattern private variables

I'm having problem with private variables in JavaScript's Revealing Prototype Pattern. I can't figure out how can I have private variables that are used in several different functions inside shared (singleton) prototype, without exposing them. Here is the example of what I mean in JSFiddle.

The problem is in using var v versus this.v. First one messes the state of all instances, but second is publicly visible. Is there a way to have v private, and preserve its state for each individual instance?

like image 942
Janez Lukan Avatar asked Nov 03 '13 08:11

Janez Lukan


People also ask

What is the revealing module pattern?

The Revealing Module pattern is a design pattern for Javascript applications that elegantly solves this problem. The central principle of the Revealing Module pattern is that all functionality and variables should be hidden unless deliberately exposed.

What is prototype design pattern in JavaScript?

The Prototype design pattern relies on the JavaScript prototypical inheritance. The prototype model is used mainly for creating objects in performance-intensive situations. The objects created are clones (shallow clones) of the original object that are passed around.

Is a design pattern which let you Organise your JavaScript code in modules and gives better code structure?

Revealing Module Pattern is JavaScript's design pattern that is available for users to actually organize JavaScript's codes in modules which actually gives better code structure and helps in making things either private or public to users.

What is modular design pattern JavaScript?

JavaScript modules are the most prevalently used design patterns for keeping particular pieces of code independent of other components. This provides loose coupling to support well-structured code. For those that are familiar with object-oriented languages, modules are JavaScript “classes”.


1 Answers

There is not a way to do that with the revealing prototype pattern.

You can only do that with something like this:

function MyClass() {
    var v = 1;
    this.getV = function() {
        return v;
    };
}

And that's why there are some die-hard enthusiasts for this kind of approach.

Personal option: Stick an underscore in front of it, and putting it on the object: this._v. Don't fight JavaScript; use it.

like image 67
Paul Draper Avatar answered Oct 02 '22 16:10

Paul Draper