DavidL
DavidL

Reputation: 51

What's going on in this piece of Javascript?

Can someone explain to me what the following Javascript is doing in terms of the constructors and how it is using / calling the function defined in the variable a?

<script>
a = 'alert("Hi");'
{}["apple"]["constructor"]["constructor"](a)();
</script>

Thanks!

Upvotes: 2

Views: 306

Answers (1)

georg
georg

Reputation: 214949

The first {} is just a bait, it's interpreted as an empty block and ignored. So we have

["apple"]["constructor"]["constructor"](a)()

which is

[].constructor.constructor(a)()

which is

Array.constructor(a)()

which is

Function(a)()

which is

(function() { alert('Hi') })()

constructors are resolved via prototypes, here's the structure:

enter image description here

Upvotes: 12

Related Questions