最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

前端模塊通常是我們開發(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,如果在瀏覽器中,通過一個字符串標(biāo)識符“_”作為一個全局對象;完整的閉包如下:
復(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的安裝和切換詳細(xì)操作步驟

    多版本node的安裝和切換詳細(xì)操作步驟

    有時候需要運(yùn)行不同的項目,node版本不一致會導(dǎo)致不少問題,下面這篇文章主要給大家介紹了關(guān)于多版本node的安裝和切換詳細(xì)操作步驟的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • nestjs搭建HTTP與WebSocket服務(wù)詳細(xì)過程

    nestjs搭建HTTP與WebSocket服務(wù)詳細(xì)過程

    這篇文章主要介紹了nestjs搭建HTTP與WebSocket服務(wù)詳細(xì)過程的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • NodeJs環(huán)境安裝與配置的實現(xiàn)步驟

    NodeJs環(huán)境安裝與配置的實現(xiàn)步驟

    本文主要介紹了NodeJs環(huán)境安裝與配置,包括配置環(huán)境和配置國內(nèi)鏡像,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-01-01
  • node 標(biāo)準(zhǔn)輸入流和輸出流代碼實例

    node 標(biāo)準(zhǔn)輸入流和輸出流代碼實例

    這篇文章主要介紹了node 標(biāo)準(zhǔn)輸入流和輸出流代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • 使用Node.js構(gòu)建微服務(wù)的方法

    使用Node.js構(gòu)建微服務(wù)的方法

    這篇文章主要介紹了使用Node.js構(gòu)建微服務(wù),將介紹微服務(wù)架構(gòu)、優(yōu)勢以及如何使用Node.js開發(fā)微服務(wù),需要的朋友可以參考下
    2022-08-08
  • 基于Node.js實現(xiàn)一鍵生成個性化二維碼

    基于Node.js實現(xiàn)一鍵生成個性化二維碼

    這篇文章主要為大家詳細(xì)介紹了如何使用Node.js、Jimp和QRCode庫,結(jié)合一個簡單的腳本,通過命令行命令來快速給二維碼加上指定的背景,打造更有個性化的二維碼,感興趣的可以了解下
    2024-03-03
  • websocket實現(xiàn)Vue?3和Node.js之間的實時消息推送

    websocket實現(xiàn)Vue?3和Node.js之間的實時消息推送

    使用?WebSocket?實現(xiàn)實時消息推送是一種高效的方式,可以在客戶端和服務(wù)器之間建立長連接,實現(xiàn)低延遲的雙向通信,以下是一個簡單的示例,展示如何在前端使用?Vue?3?和后端使用?Node.js?搭建一個?WebSocket?實現(xiàn)實時消息推送的應(yīng)用
    2024-06-06
  • axios基本用法教程示例詳解

    axios基本用法教程示例詳解

    這篇文章主要為大家介紹了axios基本用法示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • npm報版本與node.js不匹配問題及解決

    npm報版本與node.js不匹配問題及解決

    這篇文章主要介紹了npm報版本與node.js不匹配問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • node.js express中app.param的用法詳解

    node.js express中app.param的用法詳解

    express.js是nodejs的一個MVC開發(fā)框架,并且支持jade等多種模板。下面這篇文章主要給大家介紹了關(guān)于node.js express中app.param用法的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-07-07

最新評論

太仓市| 张家口市| 达拉特旗| 茶陵县| 泗阳县| 砚山县| 永修县| 乌鲁木齐县| 五华县| 旅游| 漠河县| 蕉岭县| 平凉市| 太湖县| 馆陶县| 张家口市| 榆社县| 怀安县| 正阳县| 遵义市| 淮滨县| 历史| 永登县| 冀州市| 札达县| 大厂| 手游| 边坝县| 普陀区| 泊头市| 吉木乃县| 陆川县| 抚远县| 武宣县| 西吉县| 东丰县| 重庆市| 中卫市| 荣昌县| 哈密市| 怀远县|