How can we protect the namespace of an object in Javascript?

Posted by Eduard Florinescu on Programmers See other posts from Programmers or by Eduard Florinescu
Published on 2012-08-18T12:21:49Z Indexed on 2014/06/03 15:53 UTC
Read the original article Hit count: 421

Continuing from my previous question: Javascript simple code to understand prototype-based OOP basics Let's say we run into console this two separate objects(even if they are called child and parent there is no inheritance between them):

var parent = {
    name: "parent",
    print: function(){
       console.log("Hello, "+this.name);
    }
};

var child = {
    name: "child",
    print: function(){
       console.log("Hi, "+this.name);
    }
};

parent.print()
// This will print: Hello, parent
child.print()
// This will print: Hi, child

temp =parent;
parent = child;
child = temp;


parent.print()
// This will now print: Hi, child
child.print() 
// This will now print: Hello, parent

Now suppose that parent is a library, as a HTML5 application in a browser this cannot do much harm because is practically running sandboxed, but now with the advent of the ChromeOS, FirefoxOS and other [Browser] OS they will also be linked to a native API, that would be a head out of the „sandbox”. Now if someone changes the namespace it would be harder for a code reviewer (either automated or not ) to spot an incorrect use if the namespaces changes.

My question would be: Are there many ways in which the above situation can be done and what can be done to protect this namespaces? (Either in the javascript itself or by some static code analysis tool)

© Programmers or respective owner

Related posts about JavaScript

Related posts about object-oriented