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?
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
.