Skip to content

Instantly share code, notes, and snippets.

@getify
Created June 11, 2012 13:54
Show Gist options
  • Select an option

  • Save getify/2910196 to your computer and use it in GitHub Desktop.

Select an option

Save getify/2910196 to your computer and use it in GitHub Desktop.
exploring scope isolation (sandboxing) in JS
sandbox (JSON) { // explicitly list everything to import from the outer scope
var foobar = "baz"; // scoped to this sandbox
baz = "foobar"; // still scoped to this sandbox, not auto-global.
console.log(JSON); // available!
console.log(window); // not available because not imported
console.log(this); // undefined
}
console.log(baz); // undefined
var foobar = sandbox() {
baz = function() { // NOTE: no `var` statement necessary
console.log("awesome");
};
return {
baz: baz
};
};
console.log(foobar.baz); // defined
console.log(baz); // undefined
var foobar = sandbox() {
baz = function() { // NOTE: no `var` statement necessary
console.log("awesome");
};
export baz; // borrowing this syntax from ES6 modules
};
console.log(foobar.baz); // defined
console.log(baz); // undefined
@getify
Copy link
Copy Markdown
Author

getify commented Jun 11, 2012

Another reason I'm declaring scope symbol-imports in the sandbox declaration is that I think it should be the containing code's job to declare what scope symbols the isolation can access, not the contained code itself. I really hate the import semantics in ES6 modules for that reason (in addition to the conflation with module-loading).

@juandopazo
Copy link
Copy Markdown

I'm pretty sure we'll end up using module loaders on the web and we'll only use import in the server. I'm not sure they're specified (modules are still WIP), but I wouldn't be surprised if there can be anonymous modules.

Regarding your code... I think it's a bad bad idea to drop the var keyword. Strict mode does it right by throwing an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment