1

I have the following code

<!DOCTYPE html>
<html>
  <body>

    <p id="demo">Demo Element</p>


    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

    <script>
      $('#demo').click(() => {
          console.log(this)
      })
    </script>
  </body>
</html>

When I click the #demo paragraph, this returns the window object. Why does this happen and how can I not access the #demo paragraph using this method.

2 Answers2

2

Because you created the function using the arrow syntax:

()=>{

}

If you will create the function like this, it will work:

$('#demo').click(function() {
      console.log(this)
})

More info

When using the arrow syntax for creating a function, this this element, stays as the same context of the same place you define it.

An arrow function does not create its own this, the this value of the enclosing execution context is used.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
-1

It is because you're using ECMAscript syntax. Arrow function syntax bind the data within the function to itself, whereas the regular function syntax does not.