Today, I was surprised to discover something that I didn't know about private variables in AS3. If an instance of class A has a reference to another instance of class A, then the second object's private variables are accessible to the first object. No restrictions. No special tricks. You just use
obj.variableName like any other property request. I'll show you some example code, and you can try it yourself.
First, let's set up the situation. Alice has a secret in her diary. Trudy wants to know Alice's secret, so she's going to sneak in and take a peek. Here's a simple document class that presents our story in code:
Finally, this UML-like diagram below also shows what's happening:
Next, let's look at the
Person class and see how the
peekIntoDiary() method works:
As you can see the secret value sent to the constructor gets stored in the private variable
Person instance is passed to the
peekIntoDiary() method. In this case, the Trudy object (
this) now has access to the Alice object (
trace() output reads:
Trudy is looking at Alice's secret: "I kissed a girl, and I liked it!"
Yes, Alice's private variable
_secret has just been accessed by Trudy. Bet you didn't expect that to work. I know I didn't. Don't believe me? Try it yourself. The code above compiles and runs.
It makes some sense if you consider that the
private access modifier is actually a namespace. Basically, behind the scenes, the compiler automatically creates a separate namespace for each individual class that it names private. This private namespace is only accessible to the one class for which it is defined. That's why other classes and subclasses can't access private variables. However, due to the scope of the namespace, all instances of the same class can access the private members of other instances. To be truly private, each individual instance of a class would needs its own namespace that other instances wouldn't know about. I'm not even sure if that's possible, but I have a vague idea of how it might work.
Does it matter? No, not really. You'll rarely find yourself in an situation where this behavior can be useful (see the credited link below for one possibility). I can't think of a case where this can be considered a security risk either. It's not much different than using
object["variableName"] to get at private variables in AS2. Mainly, I wanted to share because it's somewhat unexpected behavior.
Credit: Thanks to Nick Bilyk for pointing this out in a post about cloning objects.