为什么$(this)和console.log显示为同一个东西?

时间:2015-03-26 13:55:25

标签: javascript jquery dom

我理解为jQuery回调$(this)将对象(或对象数组)的引用传递给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中看到的内容(撰写本文时的最新版本):

enter image description here

2 个答案:

答案 0 :(得分:0)

现在两者都没有相同的方法:

请检查它们的长度,

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对象。

这就是为什么你在两者中看到相同的值的原因。

答案 1 :(得分:0)

您正在调用$.fn.addRootNode 中的那两行$.fnjQuery.prototype参考。所以,你所做的是为jQuery对象添加一个名为addRootNode的函数。你基本上创建了一个“jQuery插件”。

在该函数中,this 一个jQuery对象,因为你正在调用一个jQuery原型的函数。你正在某处$('#yourElement').addRootNode(),所以this是调用的jQuery对象addRootNode

由于$(this) 已经一个jQuery对象,因此this无效。 jQuery知道这一点,只返回相同的对象。