Home > Web Front-end > JS Tutorial > Encapsulation method of common modules in Node.js_node.js

Encapsulation method of common modules in Node.js_node.js

WBOY
Release: 2016-05-16 16:45:53
Original
1685 people have browsed it

Module loading and execution are packaged in Node.js so that the variables in the module file are in a closure and will not pollute global variables or conflict with others.

For front-end modules, our developers usually place the module code in a closure to avoid conflicts with others.

How to encapsulate modules common to Node.js and front-end, we can refer to Underscore.js implementation, which is a functional function module common to Node.js and front-end, view the code:

Copy code The code is as follows:

// 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._ = _;
}

Determines whether the exports exist to determine whether the local variable _ is assigned to the exports. It is backward compatible with the old require() API. If in the browser , as a global object through a string identifier "_"; the complete closure is as follows:
Copy code The code is as follows:

(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);


A closure is constructed through the function definition. call(this) is the function Called under this object to avoid internal variables from contaminating the global scope. In the browser, this points to the global object (window object), and the "_" variable is assigned to the global object "root._" for external calls.

Lo-Dash, which is similar to Underscore.js, also uses a similar solution, but is compatible with AMD module loading:

Copy code The code is as follows:
 
;(function() {

  /**ES5 이전 환경에서 '정의되지 않음'에 대한 안전한 참조로 사용됨*/
  var undefine;
    /**값이 언어 유형 객체인지 확인하는 데 사용됩니다.*/
      var objectTypes = {
        '부울': false,
        '함수': true,
        '객체': true,
        '번호': false,
        '문자열': false,
        '정의되지 않음 ': false
      };
  /**전역 개체에 대한 참조로 사용됩니다.*/
  var root = (objectTypes[typeof window] && window) || this;

  /**자유 변수 '내보내기' 감지 */
  var freeExports = objectTypes[수출 유형] && 수출 && !exports.nodeType && 수출;

  /**자유 변수 '모듈' 감지*/
  var freeModule = objectTypes[모듈 유형] && 모듈 && !module.nodeType && module;

  /**인기 있는 CommonJS 확장 `module.exports` 감지*/
  var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;

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

  // ​​Lo-Dash 노출
  var _ = runInContext();

  // ​​r.js와 같은 일부 AMD 빌드 최적화 프로그램은 다음과 같은 조건 패턴을 확인합니다.
  if (typeof 정의 == 'function' && typeof 정의.amd == 'object' && 정의.amd) {
    // AMD 로더가 있는 경우에도 Lo-Dash를 전역 개체에 노출합니다.
    // Lo-Dash가 타사 스크립트에 의해 삽입되었으며 의도되지 않은 경우
    // 다음과 같이 로드되었습니다. 모듈. 전역 할당은 Lo-Dash
    // `noContric()` 메서드를 통해 모듈에서 되돌릴 수 있습니다.
    root._ = _;

    // 익명 모듈로 정의하므로, 경로 매핑을 통해
    // "밑줄" 모듈로 참조
    정의(function() {
      return _;
    });
  }
  // ​​확인 for 빌드 최적화 프로그램이 `exports` 객체를 추가하는 경우 `define` 뒤 `exports`
  else if (freeExports && freeModule) {
    // Node.js 또는 RingoJS
    if (moduleExports) {
      (freeModule.exports = _)._ = _;
    }
    // Narwhal 또는 Rhino에서 -require
    else {
      freeExports._ = _;
    }
}
  else {
    // 브라우저 또는 Rhino에서
    root._ = _;
  }
}.call(this));

再来看看Moment .js의 封装闭包主要代码:
复主代码 代码如下:
 
(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和前端通用的模块时,可以使用以下逻辑:
复制代码 代码如下:
 
if (typeof exports !== "undefined") {
    exports.** = **;
} else {
    this.** = **;
}

即,如果exports对象存在,则将局部变量装载在exports对象上,如果不存在,则装载在全局对象上。如果加上ADM规范的兼容性,那么多加一句判断:
复制代码 代码如下:
if (typeof define === "function" && define.amd){}
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template