Javascript Namespace Help

Posted by Jason on Stack Overflow See other posts from Stack Overflow or by Jason
Published on 2010-05-31T21:13:02Z Indexed on 2010/05/31 21:23 UTC
Read the original article Hit count: 205

Filed under:

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:

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

This is a Mozilla addon if it helps context wise.

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript