-
-
Save getify/2910196 to your computer and use it in GitHub Desktop.
exploring scope isolation (sandboxing) in JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
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
Another reason I'm declaring scope symbol-imports in the
sandboxdeclaration 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 theimportsemantics in ES6 modules for that reason (in addition to the conflation with module-loading).