Search code examples
javascriptoopencapsulation

Encapsulation in Javascript


I'm pretty new to Javascript, as my SO profile will attest.

I've just been reading up on a few tutorials and come across something I don't totally understand in regards to Object Orientation and Encapsulation when applied with Javascript.

The tutorial stated that Javascript objects can be declared like this:

var myCustomObject = new Object();

And that you can give it instance variables like this:

myCustomObject.myVariable = "some value";
myCustomObject.myOtherVariable = "deadbeef";

Finally, it states that you can create a template function to create new objects like this:

function CustomObject(myVariable, myOtherVariable)
{
    this.myVariable = myVariable;
    this.myOtherVariable = myOtherVariable;
}

I also know that you can create and assign values to variables that do not yet exist and as a result are declared implicitly, as is seen in the example, where myCustomObject didn't have a myVariable, but now it does.

So, my question is: What is there to prevent new variables from being added at some other point in the code. If I'm trying to learn how an object works and what I can/should do with it, I may never see the variable additions that could well be in some other .js file, and thus not have a full understanding of the object...

Also, how do I know that some object that has just been created won't suddently turn out to have 60 more variables added later on in code that weren't mentioned at all at creation time?

How are you meant to be able to understand what an object can contain at a glance if more can just be added to it "willy nilly"?


Solution

  • Javascript objects are transformers (TM), they can turn from one form to another.

    In practise this only happens to enrich objects, never to cause harm. It allows one to for example upgrade an existing 'class' rather then subclassing or to decorate instances again removing the need to create even more 'classes'. Take the following example:

    var Vehicle = function(){}
    
    var factory = {
        create: function(name, props){
            var v = new Vehicle();
            v.type = name;
            for(var prop in props) {
                v[prop] = props[prop];
            }
        }
    }
    
    var bike = factory.create('Bike', {
        wheels: 2
    });
    
    var car = factory.create('Car', {
        wheels: 4,
        doors: 5,
        gear: 'automatic'
    });
    
    var plane = factory.create('Airplane', {
        wings: 2,
        engines: 4
    });
    

    Imagine what the code above would take without dynamic objects and you couldn't do this:

    // lets paint our car
    car.color = 'candy red';
    // bling!
    car.racingStripes = true;
    car.mirrorDice = true;
    car.furryChairs = true;
    

    You get to enrich/personalize objects in a much easier way.