Static Private Variables
Description
Privileged methods can be created by using a private scope to define the private variables or functions. The pattern is as follows.
(function(){
//private variables and functions
var privateVariable = 10;
function privateFunction(){
return false;
}
//constructor
MyObject = function(){
};
//public and privileged methods
MyObject.prototype.publicMethod = function(){
privateVariable++;
return privateFunction();
};
})();
A private scope is created to enclose the constructor and its methods. The private variables and functions are defined first, followed by the constructor and the public methods.
MyObject which is defined without var
becomes global and available
outside the private scope.
Example
(function(){// ww w . j a va 2 s . c o m
var name = "";
Person = function(value){
name = value;
};
Person.prototype.getName = function(){
return name;
};
Person.prototype.setName = function (value){
name = value;
};
})();
var person1 = new Person("CSS");
console.log(person1.getName());
person1.setName("HTML");
console.log(person1.getName());
var person2 = new Person("XML");
console.log(person1.getName());
console.log(person2.getName());
The code above generates the following result.