Understanding call and "this"

Someone passed me a better version of my drum machine. I understand most of it, but I do have some doubts:

Not really sure how index and target are working here.
It would be awesome if someone could explain these things to me!

This (document.querySelectorAll(’.drum-pad’)) returns a NodeList of classes of .drum-pad, therefore it’s not an array and can’t use regular array methods like indexOf. That’s why the first line is converting nodelist into an actual array so that later code can perform .indexOf.

I will refer you to this link to explain [].slice.call

1 Like

Exactly like @shimphillip explained it.

You could also just use the spread operator to “spread” the NodeList into elements of an array.

const dps = [...document.querySelectorAll('.drum-pad')];
1 Like

Thank you both for the replies. Now I need to figure out how index works in the handler.

Can you show where in your code handler is referenced? That will determine what this represents.

1 Like

I´m having troubles figuring out how “this” (which I assume refers to index) and target work in this context. I have a raw idea (basically, index determines a position in the dps array based on the user input) but I´m not sure.

Where is your handler function called? I already know what the handler function is, but in what part of the code is it called?

1 Like

this line here I mean

this refers to the button element actually clicked.

1 Like

Thank you. So it´s using IndexOf to look inside dps and see if the clicked button matches?

Yes, it is looking in dps to find the index of the button. If it is not there then it returns -1 and will cause target to be undefined. That is why the if(!target) return; exists in order to stop and exit the function if target is undefined.

1 Like

Thank you so much! Now it makes sense.