Skip to content

Instantly share code, notes, and snippets.

@andsve
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andsve/03ef7c2f911d3b061c55 to your computer and use it in GitHub Desktop.
Save andsve/03ef7c2f911d3b061c55 to your computer and use it in GitHub Desktop.
Faking a JavaScript "local" context + exporting predefined specific functions.
function FakeContext( src ) {
return (Function( '"use strict";' +
"if (this != window) {" +
" for (var __i in this) {" +
" eval( 'var ' + __i + ' = this[ __i ];' );" +
" }" +
"}" +
src +
"\n" +
"if (typeof(initialize) != 'undefined') { this.initialize = initialize; };" +
"if (typeof(shutdown) != 'undefined') { this.shutdown = shutdown; };" +
"return this;"
)
);
}
var a = FakeContext("console.log('This is a name:', name); function initialize() { console.log('init'); }");
var b = a.apply( { name: "John Doe" } );
b.initialize(); // Running the "exported" function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment