Markus
Markus

Reputation: 3353

Javascript: new Function() and eval()

I'm confused ... Why is the first line of eval working, but the second isn't? Is there a restriction in nesting evals and Function definition or is there an other syntax error?

function a(b,c) {console.warn(b+c);}
function d(b,c) {console.warn(b*c);}

eval('new Function("b", "c", "a(b,c); d(b,c);")')(4,5); // working
eval('new Function("b", "c", "a(b,c); eval(\"d\")(b,c);")')(4,5); // not working

PS: I know, that this kind of code is nasty - I'm just curious ...

Upvotes: 0

Views: 90

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

The problem is simply that \" becomes " when parsed, so your code becomes:

new Function("b", "c", "a(b,c); eval("d")(b,c);")

As you can see, this is not valid. Solution: double-up your backslashes: \\"d\\" should do it.

Upvotes: 3

Ry-
Ry-

Reputation: 224904

> console.log('\"d\"')
"d"

The escape sequence is interpreted by the outer string. You have to double the backslashes.

Upvotes: 3

Related Questions