繁体   English   中英

为什么$(this)和this与console.log一样显示?

[英]Why $(this) and this show up as the same thing with console.log?

我了解到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知道这一点,只是返回相同的对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM