smdrager
smdrager

Reputation: 7417

Create a private namespace independent of other javascript?

I am creating a script which may be used on a variety of websites. Since I don't know the circumstances of it's use, I'd like to be able to place it in a sandbox of sorts, where it does not affect other javascripts on the page, and is in turn not effected by other javascripts.

The most basic start is using a self-invoking 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 alert "too late!" rather than "hi!", which is not my desired effect. Can anyone help?

Upvotes: 4

Views: 101

Answers (2)

Matty F
Matty F

Reputation: 3783

Don't forget to use the var statement, if you don't use it the variable will be declared in the global scope. You're on the right track though, create your own scope within an immediately executed function. For example:

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

Going back to your example:

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

This will alert 'hi' twice, because without the var statement you are working with the same x value in both scopes. If you were to use the var statement inside the self-executing function, the second invocation of x would alert 'too late!'.

Upvotes: 5

Tadeck
Tadeck

Reputation: 137410

In both cases you forgot to add } after part with alert().

Check out this fiddle: jsfiddle.net/XSebK/2/ - it actually works as you expected and the code looks like this:

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

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

Upvotes: 1

Related Questions