简体   繁体   English

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

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

I understand that into a jQuery callback $(this) passes a reference to a DOM object (or array of objects) to jquery and constructs a jquery object and I also understand that this is the reference to the DOM object (or array of objects) the jQuery selector selected, but I don't understand why those two different objects have the same jQuery methods in the Chrome inspector: 我了解到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??

Edit: this is what I see in Google Chrome (latest release at the time of writing this): 编辑:这就是我在Google Chrome浏览器(撰写本文时的最新版本)中看到的内容:

在此处输入图片说明

Now both doesn't have same methods: 现在两者没有相同的方法:

Please check their length, 请检查它们的长度,

console.log(getMethods($(this)).length); // This returns an array of jQuery methods

returns you 174 回报你174

While

console.log(getMethods(this).length); 

returns you 109 返回您109

Update 更新资料

As you are calling both of them inside the $.fn.addRootNode and here this refers to the jQuery object. 当您在$.fn.addRootNode内部调用它们时, this是指jQuery对象。

As we know when you pass $(jquerywrappedobject) it will return that object as such as it's already a jquery object. 我们知道,当您传递$(jquerywrappedobject) ,它将返回该对象,例如它已经是一个jquery对象。

That's the reason why you're seeing same values in both. 这就是为什么您在两者中看到相同值的原因。

You are calling those 2 lines inside of $.fn.addRootNode . 您正在$.fn.addRootNode 调用这两行。 $.fn is a reference to jQuery.prototype . $.fn是对jQuery.prototype引用 So, what you did was add a function called addRootNode to jQuery objects. 因此,您addRootNode向jQuery对象添加一个名为addRootNode的函数。 You basically created a "jQuery plugin". 您基本上创建了一个“ jQuery插件”。

Inside that function, this is a jQuery object because you are calling a function that's part of the jQuery prototype. 在该函数内部, this 一个jQuery对象,因为您要调用的函数是jQuery原型的一部分。 You're doing $('#yourElement').addRootNode() somewhere, so this is is the jQuery object addRootNode was called on. 您正在某处执行$('#yourElement').addRootNode() ,因此this是调用了jQuery对象addRootNode地方。

Doing $(this) does nothing since this is already a jQuery object. $(this)不会执行任何操作,因为this 已经是一个jQuery对象。 jQuery knows this and just returns the same object. jQuery知道这一点,只是返回相同的对象。

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

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