trying to figure out 'this' in some js codes
javascript
Solution
button1.onclick = buttonClicked;
It shows `btn1` because onclick (a property of button1) now points to `buttonClicked`, so the context of this call is `button1`
button2.onclick = function(){
buttonClicked();
};
It shows `window` because onclick (a property of button2) now points to an anonymous function, and inside that function you call `buttonClicked();` (similar to `window.buttonClicked();`), the context of this call is `window`
Your case with button3:
<input type="button" value="Button 3" id="btn3" onclick="buttonClicked();"/>
is equivalent to:
btn3.onclick = function(){
buttonClicked();
}
Because when you declare your event handlers inline, the browser will automatically wraps your code inside an anonymous function.
Problem
``` <input type="button" value="Button 1" id="btn1" /> <input type="button" value="Button 2" id="btn2" /> <input type="button" value="Button 3" id="btn3" onclick="buttonClicked();"/> <script type="text/javascript"> function buttonClicked(){ var text = (this === window) ? 'window' : this.id; console.log( text); } var button1 = document.getElementById('btn1'); var button2 = document.getElementById('btn2'); button1.onclick = buttonClicked; button2.onclick = function(){ buttonClicked(); }; </script> ``` Question: when click button1, shows: `btn1`, click button2 and button3, shows:`window,` why not `btn2`, `btn3`?