通过对 this
做一些实验,我发现了以下内容:
var foo={foo:'bar',hello:'world'};
$.fn.test=function(){return this;}
$(foo).test()===$(foo); //returns false
我无法解释为什么最后的比较返回false。我确定调用函数 $(foo).test
时 this
是 $(foo)
...
$(this).test()===$(this)
也会发生同样的事情,它也返回 false;但是 $(this).test()[0]===window
按预期返回 true。
有什么解释吗?
当您执行 $(foo)
时,您正在执行一个创建新 jQuery 对象的函数。
如果您再次尝试您的示例,但通过将对象存储在变量中,它应该可以按预期工作:
var $foo = $(foo);
$foo.test()===$foo; //=> true
这是因为 JavaScript 中对象之间的比较是通过身份而不是它们的内容来完成的。
如果你了解像 C 这样的语言,你应该明白为什么,如果不了解,我会尝试解释:
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.