1. 程式人生 > >jQuery.extend()和jQuery.fn.extend()的區別

jQuery.extend()和jQuery.fn.extend()的區別

console 函數 () crystal sta html hello 實例對象 query

jQuery.extend()一般用於擴展工具函數(也可以說是基於類的擴展)

jQuery.fn.extend()一般用於擴展自定義插件,即用在jQuery實例上的插件(基於對象的擴展)

如:

<div id="test"></div>

$(doument).ready(function() {

  $.fn.extend({

    sayHello: function() {

      console.log(this.html())

    }

  })

  $("#test").sayHello(); //$("#test")即為一個實例,sayHello為作用在該實例上的方法

})

其中方法中的this即是指向調用該方法的實例對象。

如新建一個對象:

var obj = {

  name: "crystal",

  say: function() {

    console.log(this.name); //crystal

  }

}

以上代碼中的this即指向obj對象,同理,在$.fn.extend中,$("#test")即為實例對象,調用的方法sayHello()指向對象即$("test")。

jQuery.extend()和jQuery.fn.extend()的區別