Constructing private, privileged and public members of JavaScript objects
        
        
        
        
        
         
      

Two objects have been created, each one with a corresponding DIV displayed on the page. Both of the objects share a common prototype. You can confirm this by opening the developers tools from your browser and entering "Object.getPrototypeOf(div1) === Object.getPrototypeOf(div2)" into the console command line. This will return "true", proving that they share the same object as their prototypes.

The prototype is an instance of an object created using the "new" keyword on a constructor function. By using a constructor we are able to create private and privileged properties and methods. For example, from outside of the constructor you can not directly address the _nameSpace object. To confirm this go to the console and enter "div1._nameSpace". It will return "undefined" because _nameSpace is private. The GUID property is public so you can see it by entering "div1.GUID" in the console. However, even knowing that, you can not run the _getProp() method. Try entering "div1._getProp(div1.GUID,'myDiv')" and you will get "TypeError: undefined is not a function" because _getProp() is private. On the other hand, you can run "div1.getProp('myDiv')" which is a privileged method. It will then run _getProp() for you and return the result, which in this case is the div1 DIV on the page.

Each object has a GUID. That GUID is used to keep the private properties of the objects seperated in the prototype. Methods in the prototype are written to only act on the properties of the designated object. Public properties such as the GUID itself can be stored in the individual instance of each object, as can public methods. Since the GUID is stored in each instance, the privileged methods in the prototype can access the GUID of the calling object using "this.GUID". They can then pass that GUID on to the private methods. This way the calling object does not need to worry about passing it's own GUID. You can confirm this by entering "div1.getProp('myDiv')" and then "div2.getProp('myDiv')" in the console command line. You will get two different objects back, each one representing a div on the page.

A unique public method has been added to each object. Each of these methods utilize the privileged methods in the prototype to access private properties of the objects. Try these out by entering "div1.says()" and "div2.says()" in the console command line.


JavaScript Source: