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?
Don’t forget to use the
varstatement, 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:Going back to your example:
This will alert ‘hi’ twice, because without the
varstatement you are working with the samexvalue in both scopes. If you were to use thevarstatement inside the self-executing function, the second invocation ofxwould alert ‘too late!’.