问题描述
限时送ChatGPT账号..对于在线挑战,我已经对一些代码进行了反混淆处理:
For an online challenge, I've deobfuscated some code to this:
A = (0)['constructor']['constructor']
根据我的尝试,该函数将一些代码作为参数,并将其放入匿名函数的主体中并返回.
From what I've tried, this function takes some code as parameter and puts it in the body of an anonymous function and returns it.
A = (0)['constructor']['constructor']
console.log(A)
console.log(A('return 9'))
console.log(A('return 9')())
然而,我不明白这个语法以及函数是如何创建的.幕后发生了什么?
However, I don't understand this syntax and how the function is created. What's happening behind the scene ?
推荐答案
这里发生的事情数量惊人,所以我会试着把它分解成几个步骤.
There's a surprising amount going on here, so I'll try to break it down into steps.
0
是一个原始数.原语没有属性,任何检索属性的尝试(例如 (0).constructor
)都会导致 Javascript 自动将其转换为 Object 表示.例如.(0)
变成 Number(0)
.(0)
仍然是一个原语,只是增加了分组操作符()
.这样做是因为在没有括号的情况下,0.
中的 .
被解释为小数点而不是属性访问器.您可以使用 0..constructor
或许多其他方法来实现相同的目的.所有 Javascript 对象都有一个 prototype
.您可以使用对象的 __proto__
属性查看对象的原型,例如(0).__proto__
.prototype
很有趣,因为当您尝试访问对象上的属性时,Javascript 还会检查 __proto__
对象以查看该属性是否存在于其上.(这主要用于继承).__proto__
的属性之一是 constructor
.constructor
是第一次创建对象时调用的函数.constructor
属于 Function
类型,它本身是一个具有自己的 constructor
属性的对象.
0
is a primitive number. Primitives have no properties, and any attempt to retrieve a property (such as (0).constructor
) will cause Javascript to automatically convert it to an Object representation. E.g. (0)
becomes Number(0)
.
(0)
is still a primitive, just with the addition of the grouping operators ()
. This is done here because, without the parentheses, the .
in 0.
is interpreted as a decimal point rather than a property accessor. You could achieve the same thing with 0..constructor
or a number of other ways.
All Javascript objects have a prototype
. You can see an object's prototype using its __proto__
property, e.g. (0).__proto__
. The prototype
is interesting because, when you try to access a property on the object, Javascript will also check the __proto__
object to see if that property exists on it. (This is used mainly for inheritance).
One of the properties on __proto__
is constructor
. The constructor
is a function that is called when the object is first created.
constructor
is of type Function
, which is itself an object with its own constructor
property.
所以,(0).constructor.constructor
是 Number(0).__proto__.constructor.__proto__.constructor
的简写.
So, (0).constructor.constructor
is shorthand for Number(0).__proto__.constructor.__proto__.constructor
.
返回 9
的匿名函数会执行它们的操作,因为 Function
的构造函数接受一些 Javascript 代码的字符串表示作为参数.相当于这样做:
Your anonymous functions that return 9
do what they do because the constructor of a Function
accepts as an argument a string representation of some Javascript code. It's equivalent to doing this:
Function('return 9')()
;
更正了关于自动装箱和(0)
这篇关于这个函数是如何创建的?A = (0)['构造函数']['构造函数']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论