DIV CSS 佈局教程網

用 IIFE 封裝全域命名空間的實作與思路
編輯:關於JavaScript     

以下是我的測試碼,註解部分其實比程式碼本身更值得讀:

/*global window, jQuery, validate_email, masterUI, $, rest*/
/** Enable ECMAScript "strict" operation for this function. See more:
 *  https://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
 *  https://stackoverflow.com/questions/5020479/
 *
 *  Q1: Why are window and document being fed instead of just being accessed normally?
 *  A1: Generally to fasten the identifier resolution process, having them as local
 *      variables can help (although the performance improvements may be negligible).
 *  A2: Passing the global object is also a widely used technique in non-browser
 *      environments, where you don't have a window identifier at the global scope:
 *      (function (global) { ... })(this);
 *  A3: Passing window and document allows the script to be more efficiently minified.
 *
 *  Q2: Why the heck is undefined being passed in?
 *  A1: Because the undefined global property in ECMAScript 3 is mutable, meaning
 *      someone could change its value and affect your code:
 *      undefined = true;                      // mutable!
 *      (function (undefined) {
 *        alert(typeof undefined);             // "undefined", the local identifier
 *      })();                                  // <-- no value passed, undefined by default
 *      Note that undefined is actually not being passed (there's no argument on the
 *      function call), and that's one of the reliable ways to get the undefined value
 *      without using the window.undefined property.
 */
(function(window, document, undefined) {
  "use strict";
  window.test = {
    init: function () {
      "use strict";
      alert("ok");
    }
  };
})(window, document);   // no undefined parameter here, to avoid mutable window.undefined

逐條拆解這些技巧

為什麼把 window 和 document 當參數傳進來?

三個理由。第一,作為區域變數後,識別符解析可以少走一層作用域鏈,速度略快(雖然實際差距可能微乎其微)。第二,這是在非瀏覽器環境(如 Node.js)中取得全域物件的通用手法——那裡沒有 window 這個識別符,但可以寫成 (function(global){...})(this)。第三,也是最實際的:壓縮工具可以把參數重新命名為 a、b,比全域名稱 window、document 更短,壓縮率更高。

為什麼要傳 undefined?

因為 ES3 中 undefined 這個全域屬性是可寫的,任何人都能改寫它,進而汙染你的程式碼。解法是宣告一個名稱為 undefined 的參數,但呼叫時不傳任何值——於是這個區域變數自然就是 undefined,且外部無法影響它。這是取得「可信 undefined」最可靠的方式,不必依賴 window.undefined。

這段碼實際做了什麼

(function(){})() 這種立即調用函數表達式(IIFE)寫在獨立 js 檔案裡,檔案被 HTML 載入時函數立刻執行。執行結果是把 window.test 這個物件掛上去。

之後 HTML 就可以用 test.init() 的形式呼叫:

<head>
<title>AppEngine SDK</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="../../master/script/third_party/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="../../master/plugin/jquery-validation-1.9.0/jquery.validate.js"></script>
<script type="text/javascript" src="../../master/plugin/artDialog4.1.6/jquery.artDialog.js"></script>
<script type="text/javascript" src="../../master/script/app/test.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  test.init();
})
</script>
</head>

命名空間封裝的價值

全域變數是 JavaScript 中最容易累積技術債的地方。任何宣告在全域的變數,都可能被其他腳本覆蓋,反之你也可能不小心覆蓋別人的。IIFE 的價值就在於:只暴露一個刻意設計過的入口,其餘一切都關在閉包裡。

實務上還可以更进一步,用命名空間物件整理結構:

(function (window, document, undefined) {
  "use strict";
  var App = window.App || {};
  App.utils = {
    formatDate: function () { /* ... */ }
  };
  App.ui = {
    init: function () { /* ... */ }
  };
  window.App = App;
})(window, document);

至於 JSLint 抱怨的兩個問題——一個關於 undefined(在現代環境下已無實際風險),一個關於結尾的呼叫格式——只要功能正常,不必過度糾結工具的風格偏好。真正該在意的是:你的全域命名空間是否只暴露必要的东西。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved