Skip to content

Instantly share code, notes, and snippets.

@hagb4rd
Created May 5, 2018 13:48
Show Gist options
  • Save hagb4rd/5be0d131752150f3e3d5cf5045bab5c3 to your computer and use it in GitHub Desktop.
Save hagb4rd/5be0d131752150f3e3d5cf5045bab5c3 to your computer and use it in GitHub Desktop.

simple-module-pattern.md

(11:00:56)<earendel>n>var module=(function() { var arr=[1,2,3,4,5]; var sum=(a,b)=>a+b;  return { items: arr, sum: sum }; })();  module.items.reduce(module.sum); //simple module pattern. just return an object which contains all things that shall be public/accessible to the user/programmer -> exports/interface .. that way you can have all your shit in a single object not polluting the global scope @thevishy
- 13 min, 53 sec
(11:14:49)<earendel>yw. but you wouldn't want it. that module pattern is understood?
(11:19:34)<earendel>oh..maybe i should add: in the browser the global object is window (not in the browser extension context, or service workers tho) .. in node however each file is a module and has it own root scope .. but its really just a function span around it.. x=1 would still be planted onto the global scope when not x is not declared in some inner scope. just do sth like cx={} .. and add things there. cx.x = 1. and the "problem" turns into an opputunity
- 8 min, 15 sec
(11:27:49)<earendel>(function(exports, require, module, __filename, __dirname) { /* Module code actually lives in here .. that part is what you see when you open a file in node .. see it's really just a little extension to the simple module pattern .. instead o returning an object the exports object is passed into the function, and wehn you require(thatmodule) it returns exactly that exports object.. hiding the rest o the bullshit nicely and tidy */ }); 
(11:31:11)<earendel>when you have a car, you would export the steering-wheel, gas pedal, gear, breaks, .. all you need to drive it. however all the moving little parts are "hidden" .. this way i can use the car, without breaking it. the egineerer of the car makes sure it works properly.. meanwhile i can do sth else.. another module .. like racing track.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment