I got the impression that there is still a prejudice in society against the use of global variables for official purposes. In this regard, I want to give some explanations with examples that will remove any doubts and will be useful to everyone who is eager for modularity and flexibility in JavaScript development . I can not trace the sources of all the ideas below, but I do not claim their authorship, but only a creative synthesis. I also refuse to claim one universal pattern of definition of modules for all occasions, I hope it is clear to everyone that this can never happen. All of this is significantly different from the requirements of RequireJS, CommonJS, and how modules are created in node.js via module.exports, however, each of these patterns has its place, if you approach the task without fanaticism and prejudice .// File: global.js // if (typeof(window) != 'undefined') window.global = window; Function.prototype.override = function(fn) { var superFunction = this; return function() { this.inherited = superFunction; return fn.apply(this, arguments); } } // File: moduleName.js // moduleName (, ) (function(moduleName) { // console.log(' moduleName'); moduleName.publicProperty = ' '; var privateProperty = ' '; moduleName.publicMethod = function() { console.log(' publicMethod moduleName'); }; moduleName.toBeOverridden = function() { console.log(' toBeOverriden moduleName ( )'); }; var privateMethod = function() { console.log(' privateMethod moduleName'); }; } (global.moduleName = global.moduleName || {})); // File: moduleName.implementationName.js // moduleName , (function(moduleName) { // console.log(' implementationName'); // // // moduleName.publicProperty = ' '; // // // var privateProperty = ' '; moduleName.publicMethod = function() { // // console.log(' '); }; var privateMethod = function() { console.log(' '); }; // "Function.override" // moduleName.toBeOverridden = moduleName.toBeOverridden.override(function() { console.log(' : moduleName.toBeOverridden'); this.inherited(); // }); // , // - // moduleName.wrapperName = function() { // console.log(' '); moduleName.publicMethod = moduleName.publicMethod.override(function() { console.log(' : moduleName.publicMethod'); }); }; } (global.moduleName = global.moduleName || {})); // File: test.js require('./global.js'); require('./moduleName.js'); require('./moduleName.implementationName.js'); moduleName.wrapperName(); moduleName.publicMethod(); module.exports = function(req, res, callback) { res.context.data = []; db.impress.sessions.find({}).toArray(function(err, nodes) { res.context.data = nodes; callback(); }); } Source: https://habr.com/ru/post/183188/
All Articles