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?
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.
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.
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.
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”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With