CMedina CMedina - 5 days ago 5
Javascript Question

How pass parameter "this" on change event using Arrow Function

I usually have the code something like this:

HTML CODE:

<select id="mySelectOne">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>


JS CODE:

$("#mySelectOne").on("change",function(){
var value = $(this).val(); // Return the value selected
alert(value);
});


Using Arrow Function:

$("#mySelectTwo").on("change", () => {
var value = $(this).val(); //"this" is undefined
alert(value);
});


DEMO: https://jsfiddle.net/cmedina/kr1hxxtm/

When I use arrow function the value of
this
is
undefined
(Should refer to select element).

How can I pass the parameter?

Answer

You can't. That's half the point of arrow functions, they close over this instead of having their own that's set by how they're called. For the use case in the question, if you want this set by jQuery when calling the handler, the handler would need to be a function function.

But if you have a reason for using an arrow (perhaps you want to use this for what it means outside the arrow), you can use e.currentTarget instead of this if you like:

$("#mySelectTwo").on("change", e => {      // Note `e` argument
    var value = $(e.currentTarget).val();  // ...and using it here
    alert(value);
});

The currentTarget on the event object is the same as what jQuery sets this to when calling your handler.

Comments