<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
?
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns true if, in the array, it finds an element for which the provided function returns true; otherwise it returns false. It doesn't modify the array.
The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements. The every() method returns false if the function returns false for one element.
If you need a list of all matches, then you should use . filter() instead of . find() . If no match is found, .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With