Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trying to figure out 'this' in some js codes

Tags:

javascript

<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?

like image 409
user2507818 Avatar asked Jul 04 '13 03:07

user2507818


People also ask

Is there a this in JavaScript?

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.

What does some () JavaScript do?

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.

What is every () in JavaScript?

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.

What can I use instead of find in JavaScript?

If you need a list of all matches, then you should use . filter() instead of . find() . If no match is found, .


1 Answers

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.

like image 166
Khanh TO Avatar answered Sep 21 '22 14:09

Khanh TO