protected status of C++ and Java — variables shared between parent and child classes, yet not exposed as
public. This is occasionally useful, but is a little obscure to implement in JS if you don’t know how.
…Maybe this would make more sense if I showed you some code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
- Any clients of your parent constructor can view and even expose its protected members. Bad child classes can totally explode your encapsulation, and you can’t see this is happening just by looking at the parent constructor. You might partially mitigate this by making the protecteds object immutable at the end of your parent constructor, using the new Object.freeze() method added in ECMAScript 5
- Because the protecteds object is first created by the child, it’s possible for a naive maintainer to introduce bi-directionality, and add things to the protecteds object that the parent then listens to. This would then mean that your parent has to know about the implementation of its various children, which could get messy.
- If you’re used to using protecteds in Java, you might be used to a Java quirk where protected members are accessible throughout the package where they’re defined. But this implementation doesn’t give access to protecteds beyond parent and child classes .