10

I have a function like:

$(".myDropdown").hover(function() {
  $(this).find(".myDropdown-caretDown").hide();
}, function() {
  $(this).find(".myDropdown-caretDown").show();
});

If I want to use lambda function for hover callback, What can I use instead of this?

BlackJack
  • 4,476
  • 1
  • 20
  • 25
Mhd
  • 2,778
  • 5
  • 22
  • 59
  • 3
    `this` inside arrow function is the same object as `this` in the scope that defines the arrow function – Igor Sep 28 '17 at 13:35
  • 1
    One of the main ideas of arrow function is that `this` is not redefined from the parent context. If you need `this` don't use arrow functions. – arbuthnott Sep 28 '17 at 13:35
  • 4
    @Igor I believe that's why OP's asking the question. OP, my question is simply... *why?* Why go out of your way to do something that will require more work and isn't meant for that purpose? If I were following up a project and saw someone use arrow functions for event bindings I think I'd pull my hair out. – Tyler Roper Sep 28 '17 at 13:36
  • @Mhd: I was confused by the question until I've read the comments: You _are_ using _lambda functions_, that's anonymous functions, i.e. functions without a name. Your question seems about _arrow functions_, which are also anonymous functions but with a different syntax and semantic regarding the value of `this`. Maybe you should edit the question and title accordingly to avoid this confusion. – BlackJack Oct 11 '17 at 15:47

2 Answers2

10

this inside arrow function is the same object as this in the scope that defines this function:

$(".myDropdown").hover(
  e => $(e.target).find(".myDropdown-caretDown").hide(),
  ...
});
Igor
  • 15,833
  • 1
  • 27
  • 32
  • For this specific example, I can use event, but in general way, I can't use lambda function? – Mhd Sep 28 '17 at 13:42
  • 1
    "can't use lambda function" - for what? – Igor Sep 28 '17 at 13:45
  • Use lambda function and get access to `this` that refers to this function – Mhd Sep 28 '17 at 13:47
  • 1
    @Mhd You use a lambda/arrow function specifically when you *don't* want a local `this`, hence my comment above about this being a questionable approach. – Tyler Roper Sep 28 '17 at 13:49
3

What can I use instead of this?

Use event.target

$(".myDropdown").hover('click', (event) => {
    $(event.currentTarget).find(".myDropdown-caretDown").hide();
  },(event) => {
    $(event.currentTarget).find(".myDropdown-caretDown").show();
  },);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
  • 1
    In more general way, I can't use lambda function if I need `this` of local function? – Mhd Sep 28 '17 at 13:45
  • 1
    @Mhd with *lamda function*, scope of `this` is defined by the object that defines this *lamda function*. So, in your case it will belong to the function that defines this `hover` event-handler. – gurvinder372 Sep 28 '17 at 13:47