I've been reading Javascript for Hackers by Gareth Heyes and I've come across a piece of code I can't wrap my head around:
'a'.replace.call`1${/./}${alert}`
I get that the call function will assign "this" to be "1," and the first argument to the replace function will be the regex. The regex will match and the second argument will be the reference to the alert function.
What I don't understand is how "this" (which the call function sets to be "1,") gets changed back to the window object for alert to be able to successfully execute. I also don't understand how 1 gets passed to the alert function.
Any help is greatly appreciated.
Here's the evaluation table, step by step:
Step | Explanation |
---|---|
'a'.replace.call`1${/./}${alert}` |
N/A |
'a'.replace.call(['1', '', ''], /./, alert) |
Tagged template expansion |
'a'.replace.call('1,,', /./, alert) |
String conversion applied by .replace() |
'1,,'.replace(/./, match => alert(match)) |
It's technically (...args) => alert(...args) , but alert() ignores all arguments other than the first. |
alert('1') |
/./ matches once, and 1 is the content of that match. |