, , ( ), ( ), , , , , ().
, , . , . . "" .
(, , , , ):
function SomeThing() {
var privateVar;
this.setPrivateVar = function(val) {
privateVar = val;
};
this.getPrivateVar = function() {
return privateVar;
};
}
var t = new Something();
t.setPrivateVar("foo");
console.log(t.getPrivateVar());
, .
: , SomeThing, . . , SomeThing, . , , , . ( , , , / - , .)
: - ( , ), , , , , . , id, , ):
var SomeThing = (function() {
var cache = {}, idAllocator = 0;
function SomeThing() {
this.id = ++idAllocator;
cache[this.id] = {};
}
SomeThing.prototype.getPrivateVar = function() {
var data = cache[this.id];
return data && data.privateVar;
};
SomeThing.prototype.setPrivateVar = function(value) {
cache[this.id].privateVar = value;
};
SomeThing.prototype.destroy = function() {
delete cache[this.id];
};
return SomeThing;
})();
: cache . , , , . , destroy ( ), cache, id.
:
- , (
id ) - ,
SomeThing , destroy , . , JavaScript, , , cache . - ( ). ,
id , , . JavaScript , , .
, , SomeThing , , .
: , SomeThing SomeThing. JavaScript , , (, new), . SomeThing new, . , , , (Date , setHours ).