How to create private variable in a javascript class
Private variables aren't really available on javascript classes, at least not last time I checked (June 2020). And you really probably shouldn't do this, because it's extremely hacky, uses eval
in runtime code, and uhh... That's bad, right?
Anyway, it seemed like a lot of fun to figure out, so I did! And this is what we have.
It's been awhile since I made this, so it's possible the private variables don't work across different functions of the class... But I think they do?
The Test Class
class Expose {
//prefix the function with N_ to specify that we want to use private variables
// the function using the private field will be renamed without the prefix
static N_a(aparam,paramTwo){
alert(aparam);
alert(paramTwo)
//make sure we stay in the class
alert(this.verify);
//these next two will be private.
alert(privateField);
alert(privTwo);
}
static change(key,func){
this[key] = func;
}
}
Expose.verify = "cats";
The function to create private fields
function exposeVar(obj,key,bindArgs){
const exposeVar = function(obj,key,bindArgs){
const slicedArgs = Array.prototype.slice.call(arguments,3);
const func = obj['N_'+key];
// const theValue = privateValue;
for (const bindKey in bindArgs){
eval('var '+bindKey+'= bindArgs[bindKey];');
}
const g = "(function "+func.toString()+").apply(this,slicedArgs)();";
alert(g);
eval(g);
}.bind(obj,obj,key,bindArgs);
obj[key] = exposeVar;
return exposeVar;
}
Using the private field creator
// add privateField & privTwo to the 'a' function.
const exposedFunc = exposeVar(Expose,'a',{'privateField':'first private field','privTwo': "Another pviate field"});
Expose.a('got that bound',"another paramater");
//basically, do exposeVar() for every method of the class (or prototype) that starts with N_