Subj : Re: Creating classes/namespaces on the fly from existing functions? To : netscape.public.mozilla.jseng From : Jens Thiele Date : Wed Jan 12 2005 03:46 pm Shanti Rao schrieb: > >>> f = getLibrary("foo.js") >>> includeLibrary("bar.js") >>> >>> With the former, there are a few minor glitches. Consider >>> >>> js>f = {Foo: function() {this.message = 'Foo'}}; >> >> >> >> But why must getLibrary be implemented so as to use anonymous >> functions if "foo.js" contains named function declarations? >> >> /be >> > > That is exactly the problem with using an object when you really wanted > a namespace. > > For the sake of argument, assume that "foo.js" contains a named function > Foo(), and getLibrary() makes Foo() (formerly a global object in foo.js) > into a property of an object when included in another script. You mix two different things here. One question is: Are objects good enough as namespaces? => namespace creation, namespace access and merging namespaces A different one is: How namespaces relate to loading external scripts/libraries/native modules. > Now that I think about it some more, it's sufficiently confusing to > promote the minor glitch into a major irritation. It makes it very > difficult to convert a stand-along script into a library. This > conception of a getLibrary() function will probably be a failure. I don't think so or perhaps we speak about different things. First if getLibary (or getModule) loads a bunch of native objects and functions and puts them into an object (used as namespace) thats it. (no glitch) You talk about the case were the library is JS itself. Then the question is should getLibrary do different than a load/include? probably something like this: map the name to a script (search it in some path) then do the load/include or try to do some more common work like providing a (namespace) object the script can use. The latter is what I do. Though one could argue that passing the namespace object as "this" is bad. I did this, because then you can run this script with a normal interpreter and it is perfectly valid since "this" will simply be the global object. > An include() function still works, so long as you don't unintentionally > use the same global variable name in two different source files. This > highlights the fact that creating a class is very different from > creating a namespace. If you use objects as namespaces. Creating a namespace is like creating an object and associating a name to it. Jens .