Reputation: 37
what does the "this-keyword" reference to in this context:
jQuery.fn.m=function (){
console.log(this == $("#diveins")); // gives a false what does it reference to?
};
$("#diveins").m();
Upvotes: 0
Views: 98
Reputation: 781058
In a jQuery method, this
is the jQuery collection that you called the method on. So in your example, it's the collection returned by $("#diveins")
.
The reason you get false
is because every time you call $("#diveins")
you get a new collection. If you wrote:
console.log($("#diveins") == $("#diveins"));
it will also show false
.
You can use this.is("#diveins")
. This will work if you're just looking for a single element -- there doesn't seem to be an easy way to compare jQuery collections.
jQuery.fn.m=function (){
console.log(this.is("#diveins"));
};
$("#diveins").m();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="diveins"></div>
Upvotes: 1