Create private namespace independent of other javascript?

I am creating a script that can be used on various websites. Since I do not know the circumstances of its use, I would like to place it as a sandbox, where it does not affect other javascripts on the page and, in turn, is not executed by other javascripts.

The easiest start is to use the self-start function:

(function(){ x = function(){ alert('hi!'); x(); })(); 

But my problem is that if x is already assigned as such, you cannot override it:

 x = function(){ alert('too late!'); (function(){ x = function(){ alert('hi!'); x(); })(); 

This will warn "too late!" and not β€œhello!”, which is not my desired effect. Can anyone help?

+4
source share
2 answers

Remember to use the var operator, if you are not using it, the variable will be declared in the global scope. However, you are on the right track, create your own scope in an immediately executed function. For instance:

 var x = function() { alert('foo') }; (function() { var x = function() { alert('bar') } x() // 'bar' }()); x() // 'foo' 

Returning to your example:

 x = function(){ alert('too late!')}; (function(){ x = function(){ alert('hi!')}; x(); // 'hi' })(); x(); // 'hi' 

This will warn hi twice because without the var statement, you are working with the same x value in both areas. If you were to use the var statement inside the self-executing function, the second call to x warned "too late!"

+5
source

In both cases, you forgot to add } after the alert() .

Check out this script: jsfiddle.net/XSebK/2/ - it works the way you expected, and the code looks like this:

 x = function(){ alert('too late!'); }; (function(){ x = function(){ alert('hi!'); } x(); })(); 
+1
source

All Articles