2

Background

I'm just giving jQuery a go and for an hour, I could not hide an element using $([selector]).hide([milliseconds]), which in my sample code, is called when I click the element, in this case the anchor tag <a>. But I got it working in the end, but I don't understand why so. The only change I needed to make using the function keyword, instead, so this:

Note: Examples used this not "a", see edits

event => {
 $(this).hide(2000);
}

into this

function(event){
 $(this).hide(2000);
}

Question

Why does using function work and using an 'arrow' function doesn't? Is there a difference between the two?

My source code, for testing:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
    <style>
    a.test{
        font-weight: bold;
    }
    </style>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>   
    <!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
    <a href="http://jquery.com/">jQuery</a>
    <script>
        // $(document).ready(function () {
        //     // $("a").click(event => {
        //     //     alert("Thanks for visiting!");
        //     //     //prevents the opening of the link (what are the default events of other events types?)
        //     //     event.preventDefault();
        //     //     //Special Effects - http://api.jquery.com/category/effects/
        //     // });

        // });
        $("a").click(function(event){
            event.preventDefault();
            $( this ).hide(2000);
        });
        $("a").addClass("test");
    </script>
</body>
</html>

1 Answers1

3

Arrow function does not create a new scope tethered to this. So, to get around this, just use a normal function (like bellow). Alternatively, you could do $(event.currentTarget).hide(2000); inside your arrow function.

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
    <style>
    a.test{
        font-weight: bold;
    }
    </style>
    <script src="https://code.jquery.com/jquery-3.2.1.js"></script>   
    <!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
    <a href="http://jquery.com/">jQuery</a>
    <script>
        $("a").click(function(event) {$(this).hide(2000)});
        $("a").addClass("test");
    </script>
</body>
</html>
Neil
  • 14,063
  • 3
  • 30
  • 51
  • `Arrow function does not create a new scope tethered to this` - so does `this` refer to the current event? I thought that this referred the element selected. – ManWithAComputer May 26 '17 at 02:34
  • I understand it now, arrow functions do not get their create their own `this` value, instead this gets it value inherited from the scope that the function it is in. In my case, this refers to the `Window` object when using arrow functions. – ManWithAComputer May 26 '17 at 03:04