JavaScript doesn’t really deal in strictly public or private — not like common OO languages at least. Everything comes down to scope. What SOOJS is doing is only hanging things on the outside when they are needed. I will definitely call this public. But most things are defined as internal (henceforth private). But the magic of this is in the way things are defined. Let’s look at a simple object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function Dog() { this.breed = "Cocker Spaniel"; this.name = "Sally"; var internalMessage = "nope, can't see this unless you're in here"; this.externalMessage = "yeah everyone can see this"; var internallyDefinedButExternallyExposedMessage = "heck, I thought this was between us"; this.internallyDefinedButExternallyExposedMessage = internallyDefinedButExternallyExposedMessage; } // NOW, CHECK THESE OUT var sallyDog = new Dog(); sallyDog.externalMessage; // yeah everyone can see this sallyDog.internalMessage; // undefined (can’t see this) sallyDog.internallyDefinedButExternallyExposedMessage; // heck, I thought this was between us |
Okay, this example is a little confusing. Let’s walk into it. When something is added to the “this” object it becomes a property of that object. This is why sallyDog.name worked. It’s defined with this.name in the object. But a simple “var’ed” variable like internalMessage is not added as a property. However, you can add items to this at any time. I call this “external exposure” or “externally exposing” something.
Like I said all this scope talk is JavaScript theory. But it’s one of the constructs that matter most in the language. Even if you do not grok it yet, know that things like this have specific purpose and to tread lightly if you are changing things.