I just recently found out ( here) that there is a way to make variables in classes completely private in Javascript, meaning not accessible with the dot operator.
It works as such: JSFIDDLE
function PrivateRuns(startOff) {// make an object
function getRuns() {// private function used to get private variables
privateRuns -= 1; // accessable with "out" because in same scope
privateRuns = Math.max( privateRuns, 0);
return privateRuns + privateHits;
}
var privateRuns = startOff;
var privateHits = 6;
this.setRuns = function(val){ privateRuns = Math.max(val, 0); };
this.getAction = function () {// this function is of scope "this"
//out.privateHits = out.privateHits + 1;
return ( "runs n hits: "+ getRuns() +"   " );
};
}
var myRuns = new PrivateRuns(10);
myRuns.privateRuns = -10;// does not work
//myRuns.setRuns(-10);// DOES work
for( var i = 0; i < 10; i ++ ){
$("HTML").append( myRuns.getAction() +"<br>" );
}
Now I know that if used properly this has a lot of benefits, but is it really necessary? I have rarely ever seen this in tutorials, and I can't say I have personally looked for this in open-source projects.
Regarding this,
- Is it actually an error? (the site I read it mentioned it was a "hack")
This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.
- Is it a common practice, why or why not?