2

I've some questions about callback function type in jQuery.
I don't have deep knowledge about javascript.
Here are simple codes in document level.

$("input").change(function(){
  console.log(this);
});  

And

$("input").change(()=>{
  console.log(this);
});

Those log result are followings.
The first console log is the object of the input that is fired change event.
The second is the whole document. What is the difference between function() and ()=>{} ?
Please help me.
Thanks.
I've attached the simple test source code.

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
  $(document).ready(function(){
 console.log("init");
 $(".first").change(function(){
  console.log(this);
 });
 $(".second").change(()=>{
  console.log(this);
 });
  });
</script>
</head>
<body>
    <input type="text" class="first" />
    <input type="text" class="second" />
</body>
</html>
Andrew Li
  • 1,005
  • 12
  • 29

1 Answers1

1

The correct term for ()=>{} is arrow function, sometimes also referred as the fat arrow function.

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. These function expressions are best suited for non-method functions, and they cannot be used as constructors.

reference

Also, see Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?

For a more in-depth explanation with a few examples, you can read this article.

TwiN
  • 3,554
  • 1
  • 20
  • 31