How can I create static variables in Javascript?
The following example and explanation are from the book Professional JavaScript for Web Developers 2nd Edition by Nicholas Zakas. This is the answer I was looking for so I thought it would be helpful to add it here.
(function () {
var name = '';
Person = function (value) {
name = value;
};
Person.prototype.getName = function () {
return name;
};
Person.prototype.setName = function (value) {
name = value;
};
}());
var person1 = new Person('Nate');
console.log(person1.getName()); // Nate
person1.setName('James');
console.log(person1.getName()); // James
person1.name = 'Mark';
console.log(person1.name); // Mark
console.log(person1.getName()); // James
var person2 = new Person('Danielle');
console.log(person1.getName()); // Danielle
console.log(person2.getName()); // Danielle
The Person
constructor in this example has access to the private variable name, as do the getName()
and setName()
methods. Using this pattern, the name variable becomes static and will be used among all instances. This means calling setName()
on one instance affects all other instances. Calling setName()
or creating a new Person
instance sets the name variable to a new value. This causes all instances to return the same value.