I read in several posts that class methods should be added to the prototype
rather than written in the function body, e.g. for inheritance:
function MyClass() {
var privateVar = 5;
}
MyClass.prototype.getVar = function() {
return privateVar; // doesn't work!
}
But to access variables, they have to be made public:
function MyClass() {
//Some IDEs know this should be private because of the _underscore.
this._privateVar = 5;
}
MyClass.prototype.getVar = function() {
return this._privateVar; // works
}
However, I had an idea how to make class members private, but it's a bit more effort. Here I demonstrate it with an Encryption class that shifts characters:
;"use strict";
(function() {
var priv = []; //The private namespaces of EncryptionClass instances
var privCounter = 0; //Indicates the next index of priv
window.EncryptionClass = function() {
//Create new private namespace for this instance:
var p = {};
priv[privCounter] = p;
this.privI = privCounter++;
//Private class member:
p.password = (Math.random() * 200) | 0; // integer between 0 and 200
}
EncryptionClass.prototype.encrypt = function (str) {
//Fetch private namespace
var p = priv[this.privI];
var res = "";
for (var i = 0; i < str.length; i++)
res += String.fromCharCode(str.charCodeAt(i) + p.password);
return res;
};
})();
//Test:
var encryption = new EncryptionClass();
alert("Hello World\n" + encryption.encrypt("Hello World"));
Here, the privI
variable is global, but priv
is in a closure, so the private namespaces can not be accessed from outside.
I would like to know what you think about this pattern, and what disadvantages/drawbacks it has. If you like it, you are free to use it.
Aucun commentaire:
Enregistrer un commentaire