Pascal Bayer
Pascal Bayer

Reputation: 2613

Loading multiple scripts with same variables/functions

Is it possible to load multiple scripts with same variables/functions in JS, without overriding the old value of the variable. For example to create an own scope/sandbox or object for each loaded script.

Files to load:

script1:

<script>
function init() {
    do something...
}
</script>

script2:

<script>
function init() {
    do something...
}
</script>

And after loading call script1.init() or script2.init(), is this possible?

Upvotes: 0

Views: 438

Answers (2)

alex
alex

Reputation: 490153

You could wrap each section of code with a self invoking anonymous function, which will effectively namespace that section.

(function() {
    function init() {
        // do something...
     }
})();

init(); // ReferenceError

However, if you can't change the code, the second init will overwrite the first definition.

However...

And after loading call script1.init() or script2.init(), is this possible?

...is confusing. Do you already have the init() as methods of an object? If so, they won't overwrite each other.

Upvotes: 3

James Sulak
James Sulak

Reputation: 32447

Unfortunately, no. There is a single global scope on a single page.

However, by using something like the module pattern, you can make a fake namespace:

For example:

var script1 = (function() {
    var that = {};
    that.init = function() { 
      do something...
    };

    more functions...

    return that;
})();

And then call it by using script1.init();

You can find out more about the module pattern here.

Upvotes: 1

Related Questions