How can we protect the namespace of an object in Javascript?
- by Eduard Florinescu
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)