我了解到jQuery回调$(this)
将对DOM对象(或对象数组)的引用传递给jquery并构造一个jquery对象,并且我也理解这是对DOM对象(或对象数组)的引用选定的jQuery选择器,但我不明白为什么这两个不同的对象在Chrome检查器中具有相同的jQuery方法:
// Print the object methods (found here on stackoverflow)
function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
...
// into a jquery callback
console.log(getMethods($(this))); // This returns an array of jQuery methods
console.log(getMethods(this)); // This does the same - why??
编辑:这就是我在Google Chrome浏览器(撰写本文时的最新版本)中看到的内容:
现在两者没有相同的方法:
请检查它们的长度,
console.log(getMethods($(this)).length); // This returns an array of jQuery methods
回报你174
而
console.log(getMethods(this).length);
返回您109
更新资料
当您在$.fn.addRootNode
内部调用它们时, this
是指jQuery
对象。
我们知道,当您传递$(jquerywrappedobject)
,它将返回该对象,例如它已经是一个jquery对象。
这就是为什么您在两者中看到相同值的原因。
您正在$.fn.addRootNode
内调用这两行。 $.fn
是对jQuery.prototype
的引用 。 因此,您addRootNode
向jQuery对象添加一个名为addRootNode
的函数。 您基本上创建了一个“ jQuery插件”。
在该函数内部, this
是一个jQuery对象,因为您要调用的函数是jQuery原型的一部分。 您正在某处执行$('#yourElement').addRootNode()
,因此this
是调用了jQuery对象addRootNode
地方。
$(this)
不会执行任何操作,因为this
已经是一个jQuery对象。 jQuery知道这一点,只是返回相同的对象。