There are usually some modules that can be applied to both the front and back ends, but the JavaScript file is loaded into the script tag in the browser side, unlike node. js. node. JS is packaged to load into the final execution, so that the variables in each file are naturally formed in a closure and do not contaminate global variables. The browser side is usually the bare JavaScript snippet. So in order to solve the problem of front-end consistency, class library developers need to wrap the class library code inside a closure. The following code snippet extracts the definition of underscore from the famous class library.
1(function () { 2 //establish the root object, ' window ' in the browser, or ' global ' on the server.3 varRoot = This; 4 var_ =function(obj) {5 return Newwrapper (obj);6 }; 7 if(typeofExports!== ' undefined ') { 8 if(typeofModule!== ' undefined ' &&module.exports) {9Exports = Module.exports = _; Ten } OneExports._ = _; A } - Else if(typeofdefine = = = ' function ' &&define.amd) { - //Register as a named module with AMD. theDefine (' underscore ',function () { - return _; - }); - } + Else { -Root[' _ ') = _; + } A}). Call ( This);
First, it constructs a closure through the function definition and calls the this as a context object directly to avoid contaminating the internal variables to the global scope. The exports determines whether a local variable is bound to a exports by judging the existence of the variable, and is used as a case for processing in an AMD-compliant environment, depending on the existence of define variables. This refers to a global object (the Window object) only if it is in a browser environment, and the _ variable is assigned to the global object and exported as a method of a global object for external invocation.
So when designing a generic JavaScript class library at the front and back end, there are similar judgments:
if (typeof exports!== "undefined") { =else { this]. Eventproxy = eventproxy;}
That is, if the exports object exists, the local variable is mounted on the exports object, and if it does not exist, it is mounted on the global object.