JSFiddle - React, Tailwind, and code Playground
CSS
body {
white-space : pre;
}
JavaScript
'use strict';
Function.prototype.toJSON = function() {
var parts =
this.toString().match(/^\s*function[^(]*\(([^)]*)\)\s*{(.*)}\s*$/);
if (parts == null)
throw 'Function form not supported';
return [
'window.Function',
parts[1].trim().split(/\s*,\s*/),
parts[2]
];
};
Function.deserialise = function(key, data) {
return (data instanceof Array && data[0] == 'window.Function') ?
new (Function.bind.apply(Function, [Function].concat(data[1], [data[2]]))) :
data
;
};
var buf = '';
function out(str) { buf += str + '\n'; }
var test = function(where) { return 'hello ' + where; };
test = JSON.parse(JSON.stringify(test), Function.deserialise);
out(test('there'));
out('');
test = {
a : 2,
run : function(x, y, z) { return this.a + x + y + z; }
};
out(typeof test.run);
var serialised = JSON.stringify(test);
out(serialised);
out(typeof serialised);
var tester = JSON.parse(serialised, Function.deserialise);
out(tester.run(3, 4, 5));
document.body.innerHTML = buf;