欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js中對通用模塊的封裝方法

 更新時間:2014年06月06日 10:45:08   作者:  
這篇文章主要介紹了Node.js中對通用模塊的封裝方法,封裝方法參考了Underscore.js的實現(xiàn),需要的朋友可以參考下

在Node.js中對模塊載入和執(zhí)行進行了包裝,使得模塊文件中的變量在一個閉包中,不會污染全局變量,和他人沖突。

前端模塊通常是我們開發(fā)人員為了避免和他人沖突才把模塊代碼放置在一個閉包中。

如何封裝Node.js和前端通用的模塊,我們可以參考Underscore.js 實現(xiàn),他就是一個Node.js和前端通用的功能函數(shù)模塊,查看代碼:

復(fù)制代碼 代碼如下:
 
// Create a safe reference to the Underscore object for use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // 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 (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }

通過判斷exports是否存在來決定將局部變量 _ 賦值給exports,向后兼容舊的require() API,如果在瀏覽器中,通過一個字符串標識符“_”作為一個全局對象;完整的閉包如下:
復(fù)制代碼 代碼如下:

(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 use below.
  var _ = function(obj) {
    if (obj instanceof _) return obj;
    if (!(this instanceof _)) return new _(obj);
    this._wrapped = obj;
  };

  // Export the Underscore object for **Node.js**, with
  // 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 (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root._ = _;
  }
}).call(this);


通過function定義構(gòu)建了一個閉包,call(this)是將function在this對象下調(diào)用,以避免內(nèi)部變量污染到全局作用域。瀏覽器中,this指向的是全局對象(window對象),將“_”變量賦在全局對象上“root._”,以供外部調(diào)用。

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

復(fù)制代碼 代碼如下:
 
;(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的封裝閉包主要代碼:
復(fù)制代碼 代碼如下:
 
(function (undefined) {
    var moment;
    // check for nodeJS
    var hasModule = (typeof module !== 'undefined' && module.exports);
/************************************
        Exposing Moment
    ************************************/

    function makeGlobal(deprecate) {
        var warned = false, local_moment = moment;
        /*global ender:false */
        if (typeof ender !== 'undefined') {
            return;
        }
        // here, `this` means `window` in the browser, or `global` on the server
        // add `moment` as a global object via a string identifier,
        // for Closure Compiler "advanced" mode
        if (deprecate) {
            this.moment = function () {
                if (!warned && console && console.warn) {
                    warned = true;
                    console.warn(
                            "Accessing Moment through the global scope is " +
                            "deprecated, and will be removed in an upcoming " +
                            "release.");
                }
                return local_moment.apply(null, arguments);
            };
        } else {
            this['moment'] = moment;
        }
    }

    // CommonJS module is defined
    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) {
                // If user provided noGlobal, he is aware of global
                makeGlobal(module.config().noGlobal === undefined);
            }

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

從上面的幾個例子可以看出,在封裝Node.js和前端通用的模塊時,可以使用以下邏輯:
復(fù)制代碼 代碼如下:
 
if (typeof exports !== "undefined") {
    exports.** = **;
} else {
    this.** = **;
}

即,如果exports對象存在,則將局部變量裝載在exports對象上,如果不存在,則裝載在全局對象上。如果加上ADM規(guī)范的兼容性,那么多加一句判斷:
復(fù)制代碼 代碼如下:
if (typeof define === "function" && define.amd){}

相關(guān)文章

  • Node.js 數(shù)據(jù)加密傳輸淺析

    Node.js 數(shù)據(jù)加密傳輸淺析

    這篇文章主要給大家介紹的是Node.js數(shù)據(jù)加密傳輸,本文主要介紹的是明文傳輸,文中通過示例代碼介紹的很詳細,相信對于大家的理解和學(xué)習(xí)會很有幫助,有需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧。
    2016-11-11
  • 使用nodejs連接mySQL寫接口全過程(增刪改查)

    使用nodejs連接mySQL寫接口全過程(增刪改查)

    這篇文章主要給大家介紹了關(guān)于使用nodejs連接mySQL寫接口(增刪改查)的相關(guān)資料,MySQL是一種常用的關(guān)系型數(shù)據(jù)庫,它與Node.js的結(jié)合可以提供強大的數(shù)據(jù)存儲和檢索功能,需要的朋友可以參考下
    2023-12-12
  • 詳解Nodejs get獲取遠程服務(wù)器接口數(shù)據(jù)

    詳解Nodejs get獲取遠程服務(wù)器接口數(shù)據(jù)

    這篇文章主要介紹了Nodejs get獲取遠程服務(wù)器接口數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • Node.js進程管理之子進程詳解

    Node.js進程管理之子進程詳解

    本文詳細講解了Node.js進程管理之子進程,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-07-07
  • Node.js進程退出的深入理解

    Node.js進程退出的深入理解

    NodeJS可以感知和控制自身進程的運行環(huán)境和狀態(tài),也可以創(chuàng)建子進程并與其協(xié)同工作,這使得NodeJS可以把多個程序組合在一起共同完成某項工作,下面這篇文章主要給大家介紹了關(guān)于Node.js進程退出的相關(guān)資料,需要的朋友可以參考下
    2022-04-04
  • Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫進行日期格式化的實現(xiàn)方法

    Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime

    這篇文章主要介紹了Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫進行日期格式化的實現(xiàn)方法,結(jié)合具體實例形式分析了express框架引入EJS模版以及導(dǎo)入 silly-datetime 庫的格式化方法傳遞給EJS模版使用的相關(guān)操作技巧,需要的朋友可以參考下
    2023-05-05
  • node版本升級npm命令警告原因及解決

    node版本升級npm命令警告原因及解決

    這篇文章主要為大家介紹了node版本升級npm命令警告原因解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-06-06
  • 解決linux下node.js全局模塊找不到的問題

    解決linux下node.js全局模塊找不到的問題

    今天小編就為大家分享一篇解決linux下node.js全局模塊找不到的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • 淺析Node.js的Stream模塊中的Readable對象

    淺析Node.js的Stream模塊中的Readable對象

    這篇文章主要介紹了淺析Node.js的Stream模塊中的Readable對象,是Node.js入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
    2015-07-07
  • NodeJS連接MySQL數(shù)據(jù)庫并進行增刪改查操作詳解

    NodeJS連接MySQL數(shù)據(jù)庫并進行增刪改查操作詳解

    本篇是使用NodeJS的模塊MySQL操作MySQL數(shù)據(jù)庫的基礎(chǔ)教程,連接MySQL數(shù)據(jù)庫并進行增刪改查操作詳解,需要的朋友可以參考下
    2024-02-02

最新評論