user31782
user31782

Reputation: 7587

Why doesn't bind(this) use correct value of "this" in jQuery hover event listener?

Consider the following example:

function toggleDropdown() {  
  console.log($(this)[0].id);  
}
$("a").hover( toggleDropdown.bind(this) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="test" href="#">TEST LINK</a>

Similarly without jQuery similar response:

function toggleDropdown() {  
  console.log(this.id);  
}
document.getElementsByTagName("a")[0].addEventListener("mouseenter", toggleDropdown.bind(this) );
<a href="#!" id="myID">TEST LINK</a>

I don't know about plain javascript, but in jQuery isn't the value of current selector should be used in place of this?

Upvotes: 0

Views: 43

Answers (1)

Quentin
Quentin

Reputation: 944054

I don't know about plain javascript, but in jQuery isn't the value of current selector should be used in place of this?

No. Absolutely not. You used bind which explicitly prevents that.

toggleDropdown.bind(this):

  1. Takes the value of this which is window (because it is in a browser, outside of any function, not in strict mode).
  2. Creates a new function which calls toggleDropdown with that value as the this value.

So when the event listener is later called (be it by jQuery or by the standard DOM event API) it will call that new function which will call toggleDropdown with window as the this value.


If you want the this value to be determined by the event listener, then don't override it using bind.

function toggleDropdown() {  
  console.log($(this)[0].id);  
}
$("a").hover( toggleDropdown );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="test" href="#">TEST LINK</a>

function toggleDropdown() {  
  console.log(this.id);  
}
document.getElementsByTagName("a")[0].addEventListener("mouseenter", toggleDropdown );
<a href="#!" id="myID">TEST LINK</a>

Upvotes: 1

Related Questions