0

I'm experimenting with vanilla JavaScript using a button within a container, I am trying to get the button element using this and log it to the console. But the result changes depending on the way I declare the function on the click event.

Here's the HTML code:

<div class="container">
  <button id="this-button">this</button>
</div>

And here's the JavaScript code:

const containers = document.getElementsByClassName('container');
const thisButton = document.getElementById('this-button');

thisButton.onclick = () => {
  console.log(this);
};

When I click the button, the Window object is logged to the console, but if I change the arrow function for a function declaration, this way:

thisButton.onclick = function () {
  console.log(this);
};

The button element is logged to the console.
I would like to know why this happens, thanks in advance.

0 Answers0