Created
February 10, 2015 18:34
-
-
Save briancavalier/4a820b32e0d2abca89f7 to your computer and use it in GitHub Desktop.
Revisions
-
briancavalier created this gist
Feb 10, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,35 @@ var a = 123, b = 'hello'; function test(x, y) { console.log(this); return a + x + b + y; } // Serialize a function *with its captured environment* var sf = serialize(test, { a: a, b: b }); // Deserialize with captured environment var pf = parse(sf); // And call it console.log(pf(10, ', world')); function serialize(f, env) { return JSON.stringify({ src: f.toString(), env: env }); } function parse(serialized) { var parsed = JSON.parse(serialized); return createFunction(parsed.src, parsed.env); } function createFunction(src, env) { return (new Function(createFunctionBody(src, env))(env)); } function createFunctionBody(src, env) { return '"use strict";\n' + Object.keys(env).reduceRight(addVar, 'return ' + src + ';'); } function addVar(s, k) { return 'var ' + k + ' = arguments[0].' + k + ';\n' + s; }