Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Excerpt

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:

Code Block
themeRDark
languagejavascript
titleYour main script
linenumberstrue
var foo = "This is a global variable";
 
include("not_sandboxed.js");
 
console(foo); // what will this be?

And "not_sandboxed.js" contains this:

Code Block
themeRDark
languagejavascript
titlenot_sandboxed.js
linenumberstrue
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:

Code Block
themeRDark
languagejavascript
titleSandbox template
linenumberstrue
(function(){
 
	// your code here, this is the sandbox :)
 
})();

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

Code Block
themeRDark
languagejavascript
titlesandboxed.js
linenumberstrue
(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...

Code Block
themeRDark
languagejavascript
titlesandboxed.js
linenumberstrue
(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...

Code Block
themeRDark
languagejavascript
titleYour main script
linenumberstrue
var foo = "main script";
 
include("sandboxed.js");
 
console(foo); // "main script"
console(bar1()); // 1 (foo from sandboxed.js)
console(bar2()); // 2 (foo + 1)
Div
classbox
Contents

Jump to:

Table of Contents
maxLevel5

Div
classbox

See also

JS API:

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