Evaluating Functions For Transfer In Ie8
Solution 1:
For what it's worth, the problem is caused by JScript incorrectly interpreting this:
(function x() {})
as a FunctionDeclaration and not a FunctionExpression, so doing a statement-eval instead of an expression-eval. Similar to what happens with {}
object-literals without the wrapping brackets. You could get around it by doing something to more explicitly push it into parsing an expression, eg:
eval('['+myFunctionTransferString+'][0]');
But seriously don't. Never rely on the string representation of a function, it is not standardised and there are many browser differences.
You couldn't usefully preserve a function even if function decomposition were reliable, since there is much more to a function than the textual representation of its source. The closures it includes cannot be represented, and closures are ever-more common in real-world JavaScript.
I'm afraid there is no cheap way to serialise/re-instantiate JavaScript objects in general. The JSON subset is the reliable subset, the rest you'll have to code your own ad hoc serialisation formats for.
Solution 2:
Functions are not part of the JSON specification. Remember the JSON specification is a subset of JavaScript's syntax.
So your 'hacked' solution is actually the more correct one.
Solution 3:
Heres some hacked solutions:
var fn = function() { alert("some text"); }
var fnFromString = new Function("return " + fn.toString()); // functionanonymous() { returnfunction() { ... } }
fnFromString = fnFromString(); // function() { alert("some text"); }
and if you executing script immediately:
eval("(" + fn.toString() + ")()"); // fn executed.
Post a Comment for "Evaluating Functions For Transfer In Ie8"