搜尋
首頁web前端js教程Node.js中通用模組的封裝方法_node.js

在Node.js中對模組載入和執行進行了包裝,使得模組檔案中的變數在一個閉包中,不會污染全域變量,和他人衝突。

前端模組通常是我們開發人員為了避免和他人衝突才把模組程式碼放置在一個閉包中。

如何封裝Node.js和前端通用的模組,我們可以參考Underscore.js 實現,他就是一個Node.js和前端通用的功能函數模組,查看程式碼:

複製程式碼 代碼如下:
 
// Creuseate a safe below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _objapp); = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we // backwards-compatibility for the old `require()` API. If we 're in
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (type ) {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;   exports = module. 鎠{
    root._ = _;
  }

透過判斷exports是否存在來決定將局部變數_ 賦值給exports,向後相容於舊的require() API,如果在瀏覽器中,透過一個字串識別碼「_」作為一個全域物件;完整的閉包如下:



複製程式碼
程式碼如下: (function() {
  // Baseline setup
  // --------------

  / / Establish the root object, `window` in the browser, or `exports` on the server.
  var root = this;

  // Create a safe reference to the Underscore object for below below. 🎜>  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(objwr);
  };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API.
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined' 🎜>    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
}   exports = module.exports = _;
}  🎜 >    root._ = _;
  }
}).call(this);



透過function定義建置了一個閉包,call(this)是將function在this物件下調用,以避免內部變數污染到全域作用域。瀏覽器中,this指向的是全域物件(window物件),將“_”變數賦在全域物件上“root._”,以供外部呼叫。

和Underscore.js 類似的Lo-Dash,也是使用了類似的方案,只是相容了AMD模組載入的相容:




複製程式碼

程式碼如下:

 
;(function() {

  /**Used as a safe reference for `undefined` in pre ES5 environments*/
  var undefined;
    /**Used to determine if values are of the language type Object*/
      var objectTypes = {
        'boolean': false,
        'function': true,
        'object': true,
        'number': false,
        'string': false,
        'undefined': false
      };
  /**Used as a reference to the global object*/
  var root = (objectTypes[typeof window] && window) || this;

  /**Detect free variable `exports`*/
  var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;

  /**Detect free variable `module`*/
  var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;

  /**Detect the popular CommonJS extension `module.exports`*/
  var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;

/*--------------------------------------------------------------------------*/

  // expose Lo-Dash
  var _ = runInContext();

  // some AMD build optimizers, like r.js, check for condition patterns like the following:
  if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
    // Expose Lo-Dash to the global object even when an AMD loader is present in
    // case Lo-Dash was injected by a third-party script and not intended to be
    // loaded as a module. The global assignment can be reverted in the Lo-Dash
    // module by its `noConflict()` method.
    root._ = _;

    // define as an anonymous module so, through path mapping, it can be
    // referenced as the "underscore" module
    define(function() {
      return _;
    });
  }
  // check for `exports` after `define` in case a build optimizer adds an `exports` object
  else if (freeExports && freeModule) {
    // in Node.js or RingoJS
    if (moduleExports) {
      (freeModule.exports = _)._ = _;
    }
    // in Narwhal or Rhino -require
    else {
      freeExports._ = _;
    }
  }
  else {
    // in a browser or Rhino
    root._ = _;
  }
}.call(this));

再来看看Moment.js的封装闭包主要代码:
复制代码 代码如下:

(function (未定義) {
var moment;
// nodeJS をチェック
var hasModule = (typeof module !== 'unknown' && module.exports);
/*************************************
露出の瞬間
******** ****************************/

function makeGlobal(deprecate) {
var warning = false, local_moment = moment;
/*global ender:false */
if (エンダーの種類!== '未定義') {
return;
}
// ここで、「this」はブラウザの「ウィンドウ」、またはサーバーの「グローバル」を意味します
// 「モーメント」を追加` 文字列識別子を介したグローバル オブジェクトとして、
// Closure Compiler の「上級」モード用
if (非推奨) {
this.moment = function () {
if (!warned && console && console.warn) {
warn = true;
console.warn(
「グローバル スコープを介した Moment へのアクセスは "
「非推奨であり、今後の「
」」で削除される予定ですrelease.");
}
return local_moment.apply(null, argument);
};
} else {
this['moment '] = 瞬間;
}
}

// CommonJS モジュールが定義されています
if (hasModule) {
module.exports = moment;
makeGlobal(true);
} else if (typeof define = == "function" &&define.amd) {
define("moment", function (require,exports, module) {
if (module.config().noGlobal !== true) {
// ユーザーが noGlobal を指定した場合、ユーザーは global を認識します
makeGlobal(module.config().noGlobal === unknown);
}

return moment;
});
} else {
makeGlobal();
}
}).call(this);

上の画面の例は、封入Node.jsとフロントエンドで見られます。汎用的なモジュールの場合は、次の逻辑を使用できます:
复制代代码如下:

if ( typeofexports !== "未定義") {
exports.** = **;
} else {
this.** = **;
}

つまり、エクスポート オブジェクトが存在する場合は、局所的な値がエクスポート オブジェクトにロードされ、存在しない場合は、ローカル オブジェクト全体にロードされます。 🎜>
复制代码
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Java vs JavaScript:開發人員的詳細比較Java vs JavaScript:開發人員的詳細比較May 16, 2025 am 12:01 AM

javaandjavascriptaredistinctlanguages:javaisusedforenterpriseandmobileapps,while javascriptifforInteractiveWebpages.1)JavaisComcompoppored,statieldinglationallyTypted,statilly tater astrunsonjvm.2)

JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)