The encapsulation method of general module in Node.js _node.js

Source: Internet
Author: User
Tags closure function definition

The module loading and executing is packaged in the node.js, so that the variables in the module file are in a closure, not polluting the global variables, and conflict with others.

Front-end modules are usually used by our developers to put module code in a closure in order to avoid conflicts with others.

How to encapsulate Node.js and front-end general-purpose modules, we can refer to the Underscore.js implementation, he is a node.js and front-end generic function module, view code:

Copy Code code as follows:

Create a safe reference to the underscore object for use below.
var _ = function (obj) {
if (obj instanceof _) return obj;
if (!) ( This is 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._ = _;
}

By determining whether exports exists to decide to assign local variables _ to exports, backward compatibility with the old require () API, if in the browser, through a string identifier "_" as a global object; The complete closure is as follows:
Copy Code code 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 is 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 built through the function definition, and call (this) is used to lower the function to the this object to avoid contamination of the internal variables to the global scope. In the browser, this points to the Global Object (Window object) and assigns the "_" Variable to "root._" on the global object for external invocation.

Similar to the Underscore.js Lo-dash, similar scenarios are used, but compatible with the inclusion of AMD modules:

Copy Code code as follows:

;(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 was present in
Case Lo-dash is injected by a third-party script and not intended to IS
Loaded as a module. The global assignment can is reverted in the Lo-dash
module by it ' noconflict () ' method.
Root._ = _;

Define as a anonymous module so, through path mapping, it can
Referenced as the "underscore" module
Define (function () {
return _;
});
}
Check for ' exports ' on ' define ' in case a builds 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));

Let's look at the main code for encapsulation closures of moment.js:
Copy Code code as follows:

(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 ' windows ' 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 would be removed in a 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);

As you can see from the examples above, you can use the following logic when encapsulating node.js and front-end generic modules:
Copy Code code as follows:

if (typeof exports!== "undefined") {
exports.** = * *;
} else {
this.** = * *;
}

That is, if the exports object exists, the local variable is loaded on the exports object, and if it does not exist, it is mounted on the global object. If you add compatibility with the ADM specification, add one more sentence:
Copy Code code as follows:
if (typeof define = = "function" && define.amd) {}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.