javascript - jQuery 中的 this 关键字

标签 javascript jquery

<分区>

通过对 this 做一些实验,我发现了以下内容:

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

我无法解释为什么最后的比较返回false。我确定调用函数 $(foo).testthis$(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.

关于javascript - jQuery 中的 this 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34531070/

相关文章:

javascript - 将响应式菜单从 jQuery 转换为 MooTools 1.4.x

JQuery 选择器帮助

JavaScript数据访问设计

javascript - 如何在 title 属性内的 span 元素上使用 "display: none;"?

javascript - 根据输入更改 URL

javascript - Chart.js 2.x 中的自动颜色分配不再起作用,过去在 v. 1.x 中起作用

c# - 显示 .gif 并在访问服务器期间继续播放 - asp .net

javascript - 打开带有本地 URL 的选项卡时加载 CSS 文件

javascript - 取消绑定(bind)与 .live() jQuery 绑定(bind)的事件

javascript - 使用 is data 处理数组中的每个项目