module pattern for both nodejs and browser

One module pattern for both nodejs and browser

The Module Pattern is also called “design pattern”. It helps us to keep our code clean and more readable. Lot’s of design pattern exists. But this simple pattern will make your code executable in both node and browser environment, your program must be environment independent. Means you can’t use browser api in your code if you want to use in nodejs and vice versa.

Design pattern

functionToBeReturned is a function which will contain your code, and this function is returned by it’s parent anonymous function and assigned to Egret.
Then it checks if this is running in nodejs or browser by checking module and module.exports are exist or not.
Egret is assigned to module.exports for nodejs and window for browser.

If you want to learn in depth, I recommend “Learning JavaScript Design Patterns” by Addy Osmani

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories