问题
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"
)();
回答1:
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
来源:https://stackoverflow.com/questions/18635387/advanced-syntax-0constructorconstructor-how-does-it-works-to-evalua