Say I have 3 <img>
tags on a page, and I would like to get these as an array, so I wrote:
let myArray = ['img1', 'img2', 'img3'].map(id => document.getElementById(id));
... which worked well.
Then I thought, hey, getElementById
takes exactly 1 argument. Isn't there a syntax sugar for that? So I wrote:
let myArray = ['img1', 'img2', 'img3'].map(document.getElementById);
... but that didn't work. I got "Illegal invocation" on Chrome.
So it's not syntax sugar then. What's behind all these?
You can if you pass in
document
tomap()
's secondthis
argument, which will provide the correct context for callinggetElementById
. Not sure if this is an improvement over just using the arrow function, though.JavaScript has a difference between "method call" and "function call". The former will set
this
, the latter won't. Syntactically, method call must be of formreceiver.method(...args)
. No dot, no method call. So, this:When you do
map(document.getElementById)
,document.getElementById
is a function plucked from its object; whenmap
invokes it, it will invoke it without the receiver,this
will not be set, and things get bad.There is a way to save it:
bind
, which "methodifies" a function by binding a receiver to it:map(document.getElementById.bind(document))
should work.EDIT: to further illustrate it: