(info) Other great resources: Official JS API docs, Scripting Forum

Code sandboxing

A brief tutorial showing how to sandbox a chunk of code, primarily to avoid it's variables leaking on to the global scope.

 

Why Sandbox?

Sandboxing helps avoid some common pitfalls when using include(). It's my term for a self-running closure.

Let's say this is your main script:

Your main script
var foo = "This is a global variable";
 
include("not_sandboxed.js");
 
console(foo); // what will this be?

And "not_sandboxed.js" contains this:

not_sandboxed.js
var foo = "This isn't sandboxed";

When your main script runs, what will be output to the console when your script runs? Yup, "This isn't sandboxed" - the 'foo' variable in the included file overwrote the global variable of the same name in the main script.

Creating a Sandbox

A sandbox is just a self-running anonymous function, like this:

Sandbox template
(function(){
 
	// your code here, this is the sandbox :)
 
})();

So, if we now create a "sandboxed.js" that looks like this:

sandboxed.js
(function(){
 
	var foo = "This is sandboxed";
 
})();

The 'foo' variable in the sandbox is within a function, so it only exists in the scope of that function - it won't overwrite the global variable of the same name.

Choosing what to expose

Normally, external scripts won't be able to see anything in your sandbox. If you want to expose certain bits to external scripts, you can do this...

sandboxed.js
(function(_global){ // ← note the '_global' parameter added here
 
	// PRIVATE: Vars can't been seen outside of the sandbox
 
	var foo = 1;
 
	// PUBLIC: Define as methods or properties of _global object
	// Note that these functions will still be able to see foo
	// (visit 'closure' or 'scope' links above to understand why)
 
	_global.bar1 = function() { return foo; }
	_global.bar2 = function() { return foo + 1; }
 
})(this); // ← note the 'this' argument added here, it sets value of _global

Now, in your main script can see the bar1() and bar2() functions that were defined in the sandbox...

Your main script
var foo = "main script";
 
include("sandboxed.js");
 
console(foo); // "main script"
console(bar1()); // 1 (foo from sandboxed.js)
console(bar2()); // 2 (foo + 1)
Contents

Jump to:

See also

JS API:

  • include() – include an external script in to your script