Note that the module template provided by the link does not contain the properties of a private instance. It works great for function properties, since the function will not change for each instance, but is a little unlikely for value properties, as the following code shows:
var module = (function () { // private variables and functions var foo = 'bar'; // constructor var module = function (name) { // instance variables this.name=name; }; // prototype module.prototype = { constructor: module, something: function () { // notice we're not using this.foo console.log("foo in "+this.name+" is:",foo); foo="new value"; } }; // return module return module; })(); var m1 = new module("m1"); var m2 = new module("m2"); m1.something();// foo in m1 is: bar m1.something();// foo in m1 is: new value m2.something();// foo in m2 is: new value
As you can see in the last line of code, an instance of m1 and m2 has a private variable foo (all instances will point to the same value).
What I could do from another link that Bondye posted was that it was difficult to model privacy in JavaScript, and you might consider using a naming convention to indicate properties is private. You can use something like a google compiler and comment on JS code to indicate privates; but using a compiler with closure has its drawbacks (the libraries used cannot be compiled if the Closure Compiler is not compatible, and the code must be in a specific format, which must be compiled in advanced mode).
Another option is to completely throw out the prototype (at least for everything, using private properties) and put everything in the body of the constructor function (or use the function that returns the object).
// function returning an object function makeObj(name){ // private vars: var foo = "bar"; return { name:name, something:function(){ console.log("foo in "+this.name+" is:",foo); foo="new value"; } } } var m1=makeObj("m1"); var m2=makeObj("m2"); m1.something();// foo in m1 is: bar m1.something();// foo in m1 is: new value m2.something();// foo in m2 is: bar // constructor with everything in the constructor body: function Obj(name){ // private vars: var foo = "bar"; this.name=name; this.something=function(){ console.log("foo in "+this.name+" is:",foo); foo="new value"; } } Obj.prototype.someOtherFunction=function(){ // anything here can't access the "private" variables } var m1=new Obj("m1"); var m2=new Obj("m2"); m1.something();// foo in m1 is: bar m1.something();// foo in m1 is: new value m2.something();// foo in m2 is: bar
Another problem that you may encounter when using private instance values ββis that they are only available in the instance. When you want to clone an object and define the clone function in your object to create a new instance, you need to write public access functions to set private values, because you cannot set them directly, as in Java Private Fields .
Additional information on using constructor functions here: Prototypic inheritance - record