简体   繁体   中英

how to define a Function inside a Function in javascript?

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

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 :

  • a bad string literal
  • you don't call the inner function
  • you're missing quotes around the inner function body

Here's a "fixed" version :

var expr = "'use strict';\
console.log('a')";
var f = Function('"use strict";var t = Function("'+expr+'");t();');
f();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM