Advanced syntax: "0[constructor][constructor]()()" - How does it works to evaluate code?

StackOverflow https://stackoverflow.com/questions/18635387

  •  27-06-2022
  •  | 
  •  

Question

In a code obfuscator algorithm I see one step using this syntax:

0["constructor"]["constructor"](
    0["constructor"]["constructor"](
        "return \"alert()\""
    )();
)();

My knowledge of javascript help me no more ...

typeof 0                               => number
typeof 0["constructor"]                => function
typeof 0["constructor"]["constructor"] => function  

Please, can you explain what does the js interpreter do to 'handle' this code ? I cannot understand in which way could it work !

And: what does the ending "()" mean ? I cannot understand the syntax

I tried to play with firebug js console

Executing

0["constructor"]["constructor"](
    "return \"alert()\""
)();

The console outputs "alert()", (with double quotes)

I was thinked it was equivalent to an eval, but it's not. Running this:

eval( "return \"alert()\"" );

simply causes a SyntaxError: return not in function.

Executing the first snippet of this question, is fully equivalent to simply execute a alert(), so I understand that inner code think the text is like a function body and execute it, so the inner is returning "alert()"; the outer read this last string and thinks it's a function body, so execute the code, and result is that the alert is triggerred.

But, I repeat. What does it mean the syntax ? What are usefull for the "()" at the end?

0["constructor"]["constructor"](
    "some code to be evaluted"
)();
Was it helpful?

Solution

This code is finding the Function constructor, calling it to create a new function with the argument as the code for the function's body, then invoking that function immediately:

Function("Some code to be evaluated")()

It does this twice, once with the String literal "return \"alert()\"", then again with the return value from the 1st function as the body for the 2nd.

var result = Function("Some code to be evaluated")()
Function(result)()

And, it gets Function by 1st finding Number from 0, then Function from Number:

console.log(0["constructor"] === Number); // true
console.log(Number["constructor"] === Function); // true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top