javascript-private-state icon indicating copy to clipboard operation
javascript-private-state copied to clipboard

Friend syntax.

Open trusktr opened this issue 10 years ago • 0 comments

What if the private/protected property names were to be mirrored for it to work?

const sharedSecret = Symbol();

class Friendly {
   //this class has a private property (vs "slot") that it exposes to its friends
   private data[sharedSecret] = 1  // defines a slot that has a Symbol as its slot key
   constructor () {}
}

class Friend1 {
   //this class has access to the data slot of Friendly instances

   // allows us to say friendly.!data as well as this.!data?
   private data[sharedSecret] = 5

   //access uses the Symbol sharedSecret as the slot key
   reportOn(aFriend) {
     console.log(this.!data) // logs "5"
     console.log(aFriend.!data) // logs "1"
   }
  }
}

let f1 = new Friendly()
let f2 = new Friend1()
console.log(f2.reportOn(f1))

The downside of this (and the original idea) is that the classes have to be defined in the same file as the shared symbol, together, otherwise we lose privacy. If both classes live in their own module, then they must import the shared secret, which means anyone else can import the Symbol and create a new class that can read the private properties. This could get unwieldy if there are more than two classes and they begin to get large.

A good goal for the friend design, if any, should be to still allow classes to be defined in separate modules/files, while maintaining privacy.

trusktr avatar Dec 10 '15 03:12 trusktr