Reputation: 6483
I want to declare a Function inside a Function. I'm doing it like that:
var expr = "'use strict';
console.log('a')";
var f = Function('"use strict";var t = Function('+expr+');');
f();
I get the following error: Uncaught SyntaxError: Unexpected token ';' Heres the link to jsbin I need to be able to create a function with a Function inside a Function, not nested functions nor eval are acceptable here. I noticed, that anything in the expr variable is treated incorrectly. I mean whatever code I put there. So I cant put even a variable delacration inside. Btw, if I go with single statement, like
console.log('a');
it works fine and produce the expected a in the console.
The reason I need to use Function is that I want to check how strict mode works. As according to ecmascript spec (10.1.1. Strict Mode Code) theres a case that code is in a strict mode if its starting with a prologue of "use strict" or inside a strict mode. So I want to check how Function inside a Function will behave in terms of strict code.
As I found out Function inside Function doesnt have the same strict mode on. Heres the jsbin with an example. variable is not declared and its fine. Try to add "use strict" and you see an error. For more details please have a look at the last point in this list
Upvotes: 0
Views: 85
Reputation: 382122
Apart the fact this construct should really be avoided (it's slow, it can be dangerous if you're not sure of the origin of your strings, and of course dealing with quotes is painful), you have three problems :
Here's a "fixed" version :
var expr = "'use strict';\
console.log('a')";
var f = Function('"use strict";var t = Function("'+expr+'");t();');
f();
Upvotes: 3