I know, this is often discussed. But after searching around like someone out of the 19th century, I need some advice. I have no problem by declaring a "namespace", but when it comes to a prototype.foo function, I stuck. I found a way, but I don't like it:
Namespace = {}
Namespace.obj = function() {
this.foo="bar";
}
Namespace.obj.prototype.start = function() {
this.foo="fubar";
}
blah = new Namespace.obj();
blah.start();
Now, since I'm a little neurotic in case of scripting, I would like to have something like this:
Namespace = {
obj: function() {
this.foo="bar";
},
obj.prototype.start: function(tabinst) {
this.foo="fubar";
}
}
...
But then it throws an error: "Uncaught SyntaxError: Unexpected token ."
I know, this is cosmetic, but I think that there has to be a better method of declaring a "namespace" containing a class and prototype functions.
The way I would do it is using the "Module pattern".
You basically encapsulate all your "Module" logic in a self executing function that would return an object having your classes, functions, variables etc... Think of the return value as exposing your Module API.
In order to further encapsulate the "obj" class methods and constructor we could do the following:
There is also an important feature that comes for free using this pattern, which is "Private variables", consider the following:
Yes because, you cannot use this type of chaining in an object declaration
obj.prototype or obj.something here, because the language sees obj as a non-object value. You can fake such an effect like this
(see this fiddle http://jsfiddle.net/WewnF/ )
EDIT: Wow, I just noticed that what I said was already within the question. I 'm so sorry did not notice that sooner... Well the way you described yourself is the correct method of achieving this.
Otherwise you can re-write your code like this - but is not exactly what you 're after and won't work the same (since obj won't be a function itself and you will have to call its main function like this obj.main(); )
EDIT 2: See this fiddle http://jsfiddle.net/NmA3v/1/
This will have the exact same effect. Explanation : we are declaring our objects as normal properties-functions, and then use a master prototype object which containers objects with the same names as above, for example for each Namespace.obj, there is also a Namespace.prototype.obj which contains the functions we want to add in the prototype chain.
then with namespace.protoInit(), we iterate through all properties - and extract the functions from the Namespace.prototype[ key ] and add them to Namespace[ key ].prototype - succesfully extending the prototype object! A bit unorthodox, but works!
Just for kicks and to expand on the answer above. A bit more object notation oriented based on nested namespace