FreddyNoNose FreddyNoNose - 4 months ago 25
Javascript Question

Javascript IIFE code sharing between projects

Looking for pure JavaScript answers please.

Using IIFE for a JavaScript game. Actually multiple games on multiple webpages. Suppose there is a common piece of code that needs to be used by all of these games. Say for example, a diceroller; 1d20, 3d6, etc.

What is the right way to do this? Should the IIFEs all be set to the global with unique names? I worry about setting to the global (perhaps I am too worried about that).

Does the diceroller need to be passed into the game IIFE? How to do this properly?


I think you want a Revealing Module Pattern, not an IIFE Pattern.

//Revealing Module Pattern (Public & Private) w Public Namespace 'game'
var game = (function() {

    // object to expose as public properties and methods such as game.roll
    var pub = {};

    pub.roll = function () {
        //do your thing
        return randomIntFromInterval(1,6);

    function randomIntFromInterval(min,max){
        return Math.floor(Math.random()*(max-min+1)+min);

  return pub;