title: The value of this in onclick for a button
body: <p>In the code below:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
    &lt;script type="text/javascript"&gt;
      function foo() {
        console.log(this);
     }
    &lt;/script&gt;
    &lt;body&gt;
      &lt;button id="bar" onclick="foo()"&gt;Button&lt;/button&gt;
      &lt;p id="demo"&gt;&lt;/p&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Why is it that when I say <code>onclick=foo()</code> on my button and <code>console.log(this)</code> in the foo function, the <code>this</code> variable is pointing to the <code>window</code>?</p>
  
  <p>Since technically <code>onclick=foo()</code> is defined on the button so when the <code>onclick</code> function is called it should automatically set the value of <code>this</code> to the button correct? I know how to fix this but I never understood why this is happening.</p>