[]["constructor"]["constructor"](<string representing JavaScript code>)()
In JavaScript the "constructor" property returns the prototype of an object. In this case the prototype of [] is the Array class. Accessing the "constructor" property of the Array class returns the Function object. The constructor of Function object then returns a function and the body of that function is the last parameter, which is passed to the constructor. This results in the creation of a function that uses the provided string as the function's body (i.e. code), which is then instantly executed.
上面的代码行用于执行混淆的 JavaScript 代码,而不使用“eval”方法。读完这一段后,我不太能理解这行巧妙的代码。谁能解释一下到底发生了什么?
最佳答案
请注意,Array 实例的构造函数显然是Array
:
[].constructor === Array
此外,Array
的构造函数是Function
:
[].constructor.constructor === Array.constructor === Function
现在,在 JavaScript 中,Function(source)
返回一个函数实例,其源由参数给出。例如:
Function("alert(1337)");
将创建(并且类似于):
function() {
alert(1337);
}
您的代码将实例化这样的函数并立即使用 ()
调用它。这正是 eval
的行为方式。
因此,如果有帮助,您可以将代码示例缩减为:
Function(source)();
关于javascript - 聪明的 JavaScript 绕过 eval 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36606820/