Note that the module pattern provided by the link Bondye provided does not hold private instance properties. It works great for function properties since the function would not change for each instance but works a little unpredictable for value properties as the following code demonstrates:
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 both the m1 and m2 instance share a private variable called foo (all instances will point to the same value).
What I could make out from the other link that Bondye posted is that it's hard to simulate privateness in JavaScript and you could consider using a naming convention to indicate properties are private. You can use something like google closure compiler and annotate your JS code to indicate privates; but using closure compiler has it's own disadvantages (used libraries cannot be compiled unless Closure Compiler compatible and code has to be in certain format to be compiled in advanced mode).
Another option is to throw out prototype altogether (at least for everything using the private properties) and put everything in the constructor function's body (or use a function that returns an 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's 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
One more problem you can run into with using private instance values is that they are only accessible in the instance. When you want to clone an object and define a clone function in your object to create a new instance you have to write public accessor functions to set the private values because you can't set them directly as in Java private fields.
More info on using constructor functions here: Prototypical inheritance - writing up