Other great resources: Official JS API docs, Scripting Forum
Code sandboxing
- Aubergine
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:
var foo = "This is a global variable"; include("not_sandboxed.js"); console(foo); // what will this be?
And "not_sandboxed.js" contains this:
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:
(function(){ // your code here, this is the sandbox :) })();
So, if we now create a "sandboxed.js" that looks like this:
(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...
(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...
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: