DIV CSS 佈局教程網

徹底搞懂 jQuery.extend() 與 jQuery.fn.extend() 的差別
編輯:JQuery特效代碼     

一、兩者到底差在哪

在 jQuery 原始碼中,extend 同時掛在 jQuery 與 jQuery.fn 兩個物件上,底層實作相同,但掛載位置不同,導致用途完全不一樣。官方文件這樣描述:

  • jQuery.extend():Merge the contents of two or more objects together into the first object.(把多個物件合併進第一個物件)
  • jQuery.fn.extend():Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods.(把物件掛到 jQuery 原型上,擴充出新的實例方法)

二、jQuery.extend():擴充「類」本身

把 jQuery 想成一個類別。它天生會選元素、會改樣式,現在我們用 extend 給它加一個 speak() 能力:

jQuery.extend({
  speak: function () { alert("how are you!"); }
});

完整可執行的寫法:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery.extend() 與 jQuery.fn.extend() 的差別</title>
  <meta charset="utf-8">
  <script type="text/javascript" src="jquery-1.7.1.js"></script>
  <script type="text/javascript">
    (function ($) {
      $.extend({
        speak: function () { alert("how are you!"); }
      });
    })(jQuery);
  </script>
  <script type="text/javascript">
    $(document).ready(function () {
      $.speak();
    });
  </script>
</head>
<body></body>
</html>

此時 $.speak 成為 jQuery 這個類別自身的靜態方法。

但要注意:這個能力只有「代表全體的 jQuery 類別本身」能用。具體的實例($("#abc")、$("div"))並不會有這個方法。用物件導向的語言說,jQuery.extend() 擴充的是靜態方法,只與類別本身相關,與實例無關。

三、jQuery.fn.extend():擴充「實例」

先看一個關鍵等式:

jQuery.fn = jQuery.prototype = { init: function (selector, context) { /* ... */ } }

所以 jQuery.fn.extend() 擴充的是原型,也就是所有由 $() 產生的實例物件。用法必須是:

$('selector').xyz();

完整範例:

<!DOCTYPE html>
<html>
<head>
  <title>jQuery.extend() 與 jQuery.fn.extend() 的差別</title>
  <meta charset="utf-8">
  <script type="text/javascript" src="jquery-1.7.1.js"></script>
  <script type="text/javascript">
    (function ($) {
      $.fn.extend({
        speak: function () { alert("how are you!"); }
      });
    })(jQuery);
  </script>
  <script type="text/javascript">
    $(document).ready(function () {
      $("div").speak();
    });
  </script>
</head>
<body></body>
</html>

四、差異總結

面向jQuery.extend()jQuery.fn.extend()
調用者全域函式,如 $.init()、$.ajax()具體實例物件,如 $("div").each()
功能為 jQuery 類別本身新增靜態方法為所有 jQuery 實例新增方法
典型用途工具函式、命名空間撰寫第三方插件

因此絕大部分 jQuery 插件都採用 jQuery.fn.extend(),因為插件的功能終究要作用在被選到的元素上。

五、extend 作為「合併工具」的用法

基本原型

extend(dest, src1, src2, src3...);

把 src1、src2… 合併進 dest 並回傳 dest。注意這會直接改動 dest 的結構。

若只想取得合併結果而不想動到 dest,把空物件當第一個參數:

var newSrc = $.extend({}, src1, src2, src3...);

範例:

var result = $.extend({}, { name: "Tom", age: 21 }, { name: "Jerry", sex: "Boy" });
// result = { name: "Jerry", age: 21, sex: "Boy" }

規則很簡單:後面若有同名鍵,會覆蓋前面的值。

省略 dest

dest 可以省略,此時只能有一個 src,並且會被合併到呼叫 extend 的物件上:

$.extend({ hello: function () { alert('hello'); } });
// hello 被掛到 jQuery 全域物件上

$.fn.extend({ hello: function () { alert('hello'); } });
// hello 被掛到 jQuery 實例上

實務上常見的命名空間寫法:

$.extend({ net: {} });                       // 建立 net 命名空間
$.extend($.net, { hello: function () { alert('hello'); } });
$.net.hello();

深拷貝:extend(boolean, dest, src...)

另一個重載版本,第一個參數代表是否進行深層拷貝:

var result = $.extend(true, {}, {
  name: "John",
  location: { city: "Boston", county: "USA" }
}, {
  last: "Resig",
  location: { state: "MA", county: "China" }
});

深拷貝(true)的結果,巢狀的 location 會被逐層合併:

{ name: "John", last: "Resig",
  location: { city: "Boston", state: "MA", county: "China" } }

淺拷貝(false)的結果,location 會被後者整個取代:

var result = $.extend(false, {}, {
  name: "John",
  location: { city: "Boston", county: "USA" }
}, {
  last: "Resig",
  location: { state: "MA", county: "China" }
});
// { name: "John", last: "Resig", location: { state: "MA", county: "China" } }

一句話記法

$.extend() 加在「類」上,是 jQuery 自己的工具;$.fn.extend() 加在「原型」上,是每個 $() 都能用的方法。而 extend(dest, src...) 這個合併語法,是設定物件預設值時最實用的一招:

var options = $.extend({}, defaults, userOptions);
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved