Javascript Namespace Help

Soldato
Joined
7 Apr 2004
Posts
4,212
Hi,

I have a pretty big Javascript script with loads of global variables & functions in it. Then a piece of code that calls one function from this js file: myfunc();

Ok, now I have cloned this script and modified some functionality, all function prototypes and variables are named the same in both scripts. So now I have two scripts loaded and one call to myfunc(), now we have a clash because there are loads of global variables with the same names and two myfunc()s.

What I want to do is wrap this cloned script in a namespace, so that I can modify the original call to: clone.myfunc() which will call the new function, but I also want myfunc() to just refer to the original script. In other words I can't touch the original script (no permissions) and I want to be able to use both the clone and the original at runtime.

This is the script im cloning: http://pastebin.com/6KR5T3Ah

Javascript namespaces seem quite tricky :( this seems a nice namespace method:
Code:
var namespace = {
    foo: function() {
    }

    bar: function() {
    }
}

...

namespace.foo();
}

However that requires using an object, and the script (as posted above) is humongous at nearly 4000 lines, too much to objectize I think?

Anyone know a better solution to avoid namespace pollution, with one script I cant touch and one being a clone of that script. Just so I can call myfunc() and clone.myfunc() and all global variables will behave in their respected scope.

It's either that, or I go through and modify everything to have unique names, which may take a lifetime :p

This is a Mozilla extension if it helps context wise.

Thanks,

Jack
 
Why do you want to redefine functions and variables that already exist?

If you are calling both scripts at runtime then you will have access to the functions from the first script so why would you want to redefine them in the second?
 
Why do you want to redefine functions and variables that already exist?

If you are calling both scripts at runtime then you will have access to the functions from the first script so why would you want to redefine them in the second?

I'm providing alternate functionality in functions of the same name (I know that sounds a little messy), so it isn't simply a case of code reuse.

So there is the default Mozilla code in one loaded script. Then I have copied that into an extension and modified the actual functionality, this is script two. Under one condition Mozilla's code will run, under another my code will run. The problem is that clashes occur because both code bases have the same global variables and function prototypes, hence I would like to lock them to a namespace. The alternative is I go through all the code and modify the names so everything is unique, it will just be a pain as there is so much of it, maybe it would be the cleanest solution though.
 
Back
Top Bottom