Some questions about Private Name Objects

David Bruant bruant.d at gmail.com
Mon Aug 27 08:01:49 PDT 2012


Le 27/08/2012 16:55, Matthew Robb a écrit :
> SO it has to be constructed via new Name() or will it automatically 
> create Name objects when it encounters an assignment of that form? If 
> you do have to create it does that mean in order to access it at all 
> you would need to be in scope of myname2?
>
> My question I think boils down to whether access is SCOPE gated or 
> OBJECT gated:
>
> var myClass = (function(){
>   class myClass {
>     constructor(){
>       this[test] = 0;
>     }
>   }
>
>   return myClass;
> })()
>
> myClass.prototype.getTest = function() {  return this[test]  }
>
> Is the above perfectly valid?
This cannot work, because your inherited method needs an access to the 
private name in your variable 'test' (which in your example is neither 
declared nor initialized).

To rewrite your example:

var myClass = (function(){
     var test = new Name();

     class myClass {
         constructor(){
             this[test] = 0;
         }

         getTest: function(){return this[test]};
     }

   return myClass;

})();

In this rewritten version, test is being declared in an encapsulating 
function scope, getTest will naturally gets in myClass.prototype (by 
definition of what the class syntax desugars to IIRC) and your inherited 
method will have access to your private name.

David


More information about the es-discuss mailing list