Given StringMap.js and atLeastFreeNames.js from SES, one can define
the following:
// Public domain
var serialize = function s(f) {
// Find free vars in f. (This depends, of course, on
// Function.prototype.toString being unchanged.)
var source = f.toString();
var free = ses.atLeastFreeVarNames(source);
var result = ["({"];
for (var i = 0, len = free.length; i < len; ++i) {
result.push('"');
result.push(free[i]);
result.push('":(function(){try{return eval("(');
result.push(free[i]);
result.push(')")}catch(_){return {}}})()');
result.push(',');
}
result.pop();
result.push("})");
return "[" + JSON.stringify(source) + "," + result.join("") + "]";
};
// See https://gist.github.com/Hoff97/9842228 or
// http://jsfiddle.net/7UYd4/1/
// for versions of stringify that handle cycles
var t = JSON.stringify;
var d = function (env) {
return function() {
with(env[1]){
return eval("("+env[0]+")").apply(this, arguments);
}
};
};
Then you can use these definitions with inline function expressions:
var baz = {x: 1};
var serializedEnv = t(eval(s(
function bar(foo) { return ++(baz.x)+foo /*fiddle*/; }
)));
The string serializedEnv can be stashed somewhere. When it's time to
deserialize, do the following:
var env = eval(serializedEnv);
// Hook up local values if you want them
env[1].console = console;
var deserializedFn = d(env, localBindings);
--
Mike Stay - [email protected]
http://www.cs.auckland.ac.nz/~mike
http://reperiendi.wordpress.com
--
---
You received this message because you are subscribed to the Google Groups
"Google Caja Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.