为什么 $(this) 和 this 与 console.log 显示为同一事物?
Why $(this) and this show up as the same thing with console.log?
我了解 jQuery 回调 $(this)
将对 DOM 对象(或对象数组)的引用传递给 jquery 并构造 jquery 对象,我也明白这是对 jQuery 选择器选择的 DOM 对象(或对象数组)的引用,但我不明白为什么这两个不同的对象具有相同的 jQuery Chrome 检查器中的方法:
// Print the object methods (found here on Whosebug)
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
return是你174
同时
console.log(getMethods(this).length);
return是你109
更新
因为你在 $.fn.addRootNode
中调用了它们,这里 this
指的是 jQuery
对象。
正如我们所知,当您传递 $(jquerywrappedobject)
时,它将 return 该对象,因为它已经是一个 jquery 对象。
这就是您在两者中看到相同值的原因。
您在 $.fn.addRootNode
的 中调用了 中的那两行。 $.fn
是对 jQuery.prototype
的 引用 。因此,您所做的是向 jQuery 个对象添加一个名为 addRootNode
的函数。您基本上创建了一个 "jQuery plugin".
在该函数中,this
是 一个 jQuery 对象,因为您调用的函数是 jQuery 原型的一部分。你在某处做 $('#yourElement').addRootNode()
,所以 this
是 jQuery 对象 addRootNode
被调用。
执行 $(this)
没有任何作用,因为 this
已经 一个 jQuery 对象。 jQuery 知道这一点,只是 returns 同一个对象。
我了解 jQuery 回调 $(this)
将对 DOM 对象(或对象数组)的引用传递给 jquery 并构造 jquery 对象,我也明白这是对 jQuery 选择器选择的 DOM 对象(或对象数组)的引用,但我不明白为什么这两个不同的对象具有相同的 jQuery Chrome 检查器中的方法:
// Print the object methods (found here on Whosebug)
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
return是你174
同时
console.log(getMethods(this).length);
return是你109
更新
因为你在 $.fn.addRootNode
中调用了它们,这里 this
指的是 jQuery
对象。
正如我们所知,当您传递 $(jquerywrappedobject)
时,它将 return 该对象,因为它已经是一个 jquery 对象。
这就是您在两者中看到相同值的原因。
您在 $.fn.addRootNode
的 中调用了 中的那两行。 $.fn
是对 jQuery.prototype
的 引用 。因此,您所做的是向 jQuery 个对象添加一个名为 addRootNode
的函数。您基本上创建了一个 "jQuery plugin".
在该函数中,this
是 一个 jQuery 对象,因为您调用的函数是 jQuery 原型的一部分。你在某处做 $('#yourElement').addRootNode()
,所以 this
是 jQuery 对象 addRootNode
被调用。
执行 $(this)
没有任何作用,因为 this
已经 一个 jQuery 对象。 jQuery 知道这一点,只是 returns 同一个对象。