Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  39] [ 2]  / answers: 1 / hits: 16805  / 7 Years ago, mon, october 30, 2017, 12:00:00

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.


More From » onclick

 Answers
16

in my opinion it is because you did not pass your button to your function like this :



<input type=button value=mybutton1 onclick=dosomething(this.value)>


while your code is like this:



<button id=bar onclick=foo()>Button</button>


and the entry of your function is empty:



    <script type=text/javascript>
function foo() {
console.log(this);
}
</script>


so you should pass this to your function like this:



   <script type=text/javascript>
function foo(e) {
console.log(e);
}
</script>


and because the value of this is not set by the call, this will default to the global object , which is window in a browser.



for more info please check this out.


[#56069] Friday, October 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;