1

By doing some experiments with this ,I came upon the following:

var foo={foo:'bar',hello:'world'};
$.fn.test=function(){return this;}
$(foo).test()===$(foo); //returns false

I cannot explain why the last comparison returns false. I am sure that this when calling function $(foo).test is $(foo)... The same thing happens with $(this).test()===$(this) which returns also false; however $(this).test()[0]===window returns true as expected.

Any explanation?

Unknown developer
  • 5,414
  • 13
  • 52
  • 100
  • 7
    Comparing two objects, even if they have the same content, is never true. Two objects are always different. – adeneo Dec 30 '15 at 14:05

1 Answers1

3

When you do $(foo), you are executing a function that creates a new jQuery object.

If you try your example again but by storing the object in a variable it should work as you expect:

var $foo = $(foo);
$foo.test()===$foo; //=> true

This is because comparison between objects in JavaScript is done by identity, not by their content.

If you know a language like C you should understand why, if not I'll try to explain:

var x = { a: 1 };
// What happens in memory is that the variable x stores a pointer to a location
//  in memory with the actual content. So in C, if you tried to print x, you
//  would get a long number instead of the actual object, eg: 2435080915
var y = { a: 1 };
// Now we created another object with the same content, but the content is
//  duplicated in memory, it's not at the same place than x, because if it was, 
//  a modification to y would also affect x. So the pointer is
//  another number, eg: 7043815509

// So when we do:
x == y
// what happens is that JavaScript compares the two numbers:
// 2435080915 == 7043815509
// which returns false.
lleaff
  • 4,249
  • 17
  • 23