Reputation: 7587
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
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)
:
this
which is window
(because it is in a browser, outside of any function, not in strict mode).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