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