0

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();
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) –  Dec 20 '16 at 19:08

1 Answers1

1

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>
Barmar
  • 596,455
  • 48
  • 393
  • 495