Onclick JavaScript Event

0

I'm testing Onclick on JS and I'm strange about a business, it works only when I paste it into the document.querySelector('.a').onclick = teste2(); console, or the first time I run / open the page. If I click on the element I'm catching, it does not work. Why?

<html>
<head></head>
<meta charset="utf-8">
<body>

<div class="a">Testando...</div>

    <script>
      
      let teste2 = () => alert(this === window);
      document.querySelector('.a').onclick = teste2();

    </script>

</body>
</html>
    
asked by anonymous 03.06.2018 / 05:22

1 answer

3
The onClick method receives a function so that it is instantiated when there is click , in your example you store the function in a variable and pass it instantiated when the correct one would only pass the variable ...

<html>
<head></head>
<meta charset="utf-8">
<body>

<div class="a">Testando...</div>

    <script>
      
      let teste2 = () => alert(this === window);
      document.querySelector('.a').onclick = teste2;

    </script>

</body>
</html>
    
03.06.2018 / 05:36