Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JQuery, why does $(this) == $(this) return false? [duplicate]

I have run the following lines in my console (once a jquery script has been loaded), and received the following results:

$(this)
> [Window]
$(this) != $(this)
> true
$(this) == $(this)
> false
$(this) === $(this)
> false

And I don't know what steps to take to figure out what is going on. My guess is that there is some object that holds a time based value which is changing, but I wonder if it's something different. I will try to compare the values in the meantime, but I was hoping someone might understand what is going on here.

Edited to address the point that I was unaware of the underlying implementation of $(arg). I did not know that it returned a new reference object. Therefore, I don't believe this is a duplicate of "How to determine equality for two JavaScript objects?".

like image 396
NicholasFolk Avatar asked Feb 18 '17 19:02

NicholasFolk


1 Answers

Using $() returns an instance of jQuery. So, you create one instance with this, and another instance of this, you have two separate instances. Even though they share the same reference to this, the instances are not the same, and those are what is being compared.


It might help to have a visual example, and might make things a little more clear. jQuery operates like a class. So let's use an very simple example where for example's sake, the function $() doesn't exist:

class jQuery {
    constructor(element) {
        this.element = element;
    }
}

var obj1 = new jQuery(this);
var obj2 = new jQuery(this);

console.log(obj1 === obj2); // false

Both of those are using the exact same argument (this) to create a new "jQuery" object. But, once again, obj1 is a completely different instance than obj2. They both have their own unique place in memory.

like image 62
KevBot Avatar answered Oct 02 '22 20:10

KevBot