Understanding call and "this"

Understanding call and "this"
0

#1

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!


#2

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


#3

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')];

#4

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


#5

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


#6

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.


#7

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


#8

this line here I mean


#9

this refers to the button element actually clicked.


#10

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


#11

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.


#12

Thank you so much! Now it makes sense.