I'm just getting in to Javascript, so my first attempt at namespaces ended up looking like this:
var myNameSpace = {};
var myNameSpaceProto = myNameSpace.__proto__;
myNameSpaceProto.SomeFunc = function()
{
alert("SomeFunc()");
};
myNameSpaceProto.SomeObject = function()
{
alert("SomeObject constructor");
};
var instance = new myNameSpace.SomeObject();
I gather I can safely skip the prototype step and simply have myNameSpace.SomeFunc = function...
, because there's only ever one myNameSpace
object instance so the prototype doesn't save anything.
Question 1: Is this correct? I want to add to the namespace from several separate .js files, so this way seems convenient.
Question 2: With the above code snippet I found a weird side-effect of namespace pollution, which is shown by the following SomeObject
body:
myNameSpaceProto.SomeObject = function()
{
// As expected NonexistantFunc is not a member of this and returns "undefined"
alert("typeof this.NonexistantFunc = " + typeof this.NonexistantFunc);
// Returns 'function'. How has SomeFunc made it to this.SomeFunc? It's supposed to be under myNameSpace.SomeFunc
alert("typeof this.SomeFunc = " + typeof this.SomeFunc);
// Turns out it's in the prototype's prototype. Why?
alert("this.__proto__.__proto__.SomeFunc = " + this.__proto__.__proto__.SomeFunc);
};
This was tested on Chrome 8 and I can't figure out how SomeObject
has come to have SomeFunc
as a member. This seems to be a hole in my limited knowledge of prototypes. Can someone explain?