In the classical object-oriented programming, it is often necessary to encapsulate or hide a state of an object in the object, only through the object's amplitude and access to these states, exposing only some important state variables can read and write directly.
We can simulate implementing a private instance field by decorating the variable (or parameter) within a constructor, and invoking the constructor creates an instance.
function Range ( from, to) { //do not save the battle as an object's property, instead//define accessor functions to return the value of the endpoint//These values are saved in the closure This. from=function () {return from;} This. To=function () {returnto ;}} Range.prototype={constructor:range, includes:function (x) {return This. from() <=x && x<= This. to ();},foreach: function (f) { for(varX=math.ceil ( This. from()), max= This. to (); x<=max;x++;) f (x); }, Tostring:function () {return "("+ This. from() +"..."+ This. to () +")"; }}//Call:varR=NewRange (0,5);//a range that cannot be modifiedR. from=function () {return 0; }//to modify it by this method
It is important to note that this encapsulation technology creates more overhead for the system. Classes that use closures to close the state of a class must run slower and consume more memory than equivalent classes that do not use encapsulated state variables.
From the JavaScript Authority guide 9.6.6
JavaScript uses decorative simulation to implement private state