4

As I was fooling around with XSS challenges, I encountered weird behavior when creating Function object using template strings (`` instead of parentheses) in Javascript.

As i understand, when invoking

alert`1`

It is essentially the same as

alert(["1"])

as described here. I tested many cases and everywhere it worked that way - except when Function object is created using template strings.

When executing following code:

var x = new Function`alert(1)`;
console.log(x.constructor);

instance of Object class is created with alert(1) function in it's constructor body so it's executed immediately.

If i understand correctly, it should be executed the same as

var y = new Function(["alert(1)"]);
console.log(y.constructor)

and should just return Function object with alert(1) in body so it can called like this

var y = new Function(["alert(1)"]);
y();

Where does this inconsistency come from or are template strings handled differently when creating objects?

1
  • 1
    you never save the intermediary Function, just the blank object new made Commented Aug 27, 2018 at 19:04

1 Answer 1

4

You are misunderstanding the precedence of various pieces of the language grammar.

var x = new Function`alert(1)`;

is equivalent to

var x = new (Function`alert(1)`);

so what you're essentially doing is

var fn = Function`alert(1)`;
var x = new fn;

so you've created the function, and then called it with new.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks that makes sense now! Just wondering - why calling new on Function instance creates Object instance with constructor alert(1)? It is a bit unclear to me how that second line works.
You're essentially doing var fn = function(){ alert(1); }; new fn;. Does that clarify it?
Okay i got it. Didn't know that I can call something like var x = new function(){this.val="property"; alert(1);} and it will create new object using that function as constructor. Thanks for help.
(Hint, hint: just omit the new, it's not necessary to create a Function)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.