0

I have this function:

$(".tabstrip li").each(function () {
        $(this).attr("id") == "searchlist" ? $(this).addClass("selected") : $(this).removeClass("selected");
    })

Now i was asking myself, if I can make this shorter. So I tried this:

$(".tabstrip li").each(() => $(this).attr("id") == "searchlist" ? $(this).addClass("selected") : $(this).removeClass("selected"))

And it don't worked. How I understood arrow functions this should be correct.

(There is no error too)

Do someone understand this? Its not important but I cant sleep until i figure out why this don't work ;)

Thank you for your time ^^

Lotok
  • 7
  • 4

2 Answers2

3

Arrow functions set the value of this inside them so it is the same as the value of this outside them.

This breaks your code, because a regular function called by each will have a value of this based on the current value being looped over (and your function depends on that being the case).


Do not use arrow functions "to make code shorter". That isn't what they are for. Arrow functions are for controlling the value of this.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You can make it short like this. I don't think using ES6 Arrow Functions is the best for browser support.

$(".tabstrip li").each(function () {
    $(this).toggleClass("selected", this.id == "searchlist");
})
rrk
  • 15,677
  • 4
  • 29
  • 45
  • I have to toggle off "selected" from the other
  • that is selected when I'm on "index". But thank you for your answer :D
  • – Lotok Jun 09 '16 at 15:24