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?
2 Answers 2
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(),
...
});
answered Sep 28, 2017 at 13:37
Igor
15.9k1 gold badge29 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Mhd
For this specific example, I can use event, but in general way, I can't use lambda function?
Igor
"can't use lambda function" - for what?
Mhd
Use lambda function and get access to
this that refers to this functionTyler Roper
@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.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();
},);
answered Sep 28, 2017 at 13:38
gurvinder372
68.6k11 gold badges78 silver badges98 bronze badges
2 Comments
Mhd
In more general way, I can't use lambda function if I need
this of local function?gurvinder372
@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.Explore related questions
See similar questions with these tags.
lang-js
thisinside arrow function is the same object asthisin the scope that defines the arrow functionthisis not redefined from the parent context. If you needthisdon't use arrow functions.this. Maybe you should edit the question and title accordingly to avoid this confusion.