0

I'm start studying javascript. and closure.

I met the example below.

var tabs = document.querySelectorAll('.tab');
        
function tabsHandler(index) {
    return function tabClickEvent(event) {
        console.log(index);
    };
}

for (var i = 0; i < tabs.length; i += 1) {
     tabs[i].onclick = tabsHandler(i);
}

And I was curious what would happen if there was no function inside.
like this

function tabsHandler(index) {
    console.log(index);
}

So I didn't even click it, but everything was printed out.
And I tried a lot of changes to solve it. like this.

for (var i = 0; i < tabs.length; i += 1) {
    tabs[i].onclick = (i) => console.log(i)
}

Now that I've done this, it's called Pointer Event. It's my first time seeing it
and I don't know that and can't even guess how it came out.

PointerEvent console.log photo

so my question is

  1. Why shoduld I have to use "return"?
  2. If I don't write "return", why is "onclick" ignored?
  3. Why did the PointerEvent come out?

Thank you for reading it.

young
  • 1
  • If you call `tabsHandler(i)`, and it just directly logs `i`, well, that's what it does. You want `tabsHandler(i)` to *return a function*, which you assign to `onclick`, so *a function is assigned to `onclick`* and will be called when you click. See the duplicate as for why you'd want that. — `(i) => console.log(i)` takes the argument that `onclick` passes at calltime and logs it, which is a pointer event. It shadows the `i` from the loop. – deceze Jan 24 '22 at 07:31

0 Answers0