I have come up with an idea for adding privacy support in JavaScript. I haven't found something similar in the net, so I'm thinking it's probably because the idea is bad, but yet, I want to see some response, just to be sure.
var util = {
s4: function() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
},
guid: function() {
return util.s4() + util.s4() + '-' + util.s4() + '-' + util.s4() + '-' +
util.s4() + '-' + util.s4() + util.s4() + util.s4();
}
};
// template
var Class = (function() {
var privates = {};
var getPrivates = function(obj) {
return privates[ obj.getGUID() ];
};
function Class() {
var guid = util.guid();
privates[guid] = {};
this.getGUID = function() {
return guid;
};
};
return Class;
})();
var MyClass = (function() {
var privates = {};
var getPrivates = function(obj) {
return privates[ obj.getGUID() ];
};
function MyClass(a, b) {
var guid = util.guid();
privates[guid] = {};
this.getGUID = function() {
return guid;
};
var private = getPrivates(this);
private.a = a;
this.b = b;
};
return MyClass;
})();
var obj = new MyClass("private", "public");
console.log(obj.a, obj.b);