首页 > jquery的实例对象调用方法时, this和$(this)有什么区别?

jquery的实例对象调用方法时, this和$(this)有什么区别?

网上搜到的, 全是说jquery中的this和$(this). 我的问题是,调用的方法已经是一个jquery对象了, 此时方法里的this和$(this)有什么区别. 具体看代码.

<body>
  <button class="btn btn-primary">Click Me</button>
  <div id="test">This is a test div</div>

  <script type="text/javascript">
  (function($){
    $.fn.test = function(){
      this.hide(3000);
      // $(this).hide(3000); 这样写也能实现div隐藏
      console.log(this);//[div#test, context: document, selector: "#test"]
      console.log($(this));//[div#test, selector: "#test", context: document]
      console.log(this instanceof jQuery);//true
      console.log($(this)  instanceof jQuery);//true
      console.log(this == $(this))//false
    };
  }(jQuery));

$(function(){
  $("button").click(function(){
    $("#test").test();
  });
});
  </script>

按照输出来看. 这两个都是jquery的实例对象, 而且看起来都指向了同一个对象, 但是又不相等. 用console.log()输出时看起来也只是个顺序的差别. 那么这两个对象到底是哪里存在差异呢?
按照我的理解,jquery构造函数, 可以接受选择器或者JS的DOM节点做参数, 生成一个jquery的实例对象, 但是当传入的参数本身就是一个jquery的实例对象的时候, 虽然不会报错, 但是生成的实例就不是传入的这个实例对象本身. 比如:

$(function(){
  $("button").click(function(){
    var t = document.getElementById("test");
    $(t).hide();//成功隐藏
    var d = $("#test");
    $(d).hide();//能隐藏
  });
});

上一个例子中, 显然this是指向了一个jquery的实例对象
新手初步刚刚接触jquery, 概念不清, 望指教.


第一个问题基本没区别 只有context可能变

https://github.com/jquery/jquery/blob/2.2-stable/src/core/init.js#L103-L106

$(this)的实现

        // HANDLE: $(DOMElement)
            this.context = this[ 0 ] = selector;
            this.length = 1;
            return this;

第二问题时因为你写错了...
var d = $("#test");//这个是ID选择器...

【热门文章】
【热门文章】