Search code examples
javascriptes6-modulesiife

Exporting IIFE formated function to ES6 Module


Having a little trouble with modules / IIFE etc. I have a script that used to be an IIFE and uses a lot of this key word etc.. I am trying to turn it into a module.

I have the following module dice.js:

export default function () {
this.createDice = function() { ... }
... 
}

on the main APP I call it as:

import Dice from "./dice.js";

let DICE = new Dice();
let dice1 = DICE.createDice();
let dice2 = DICE.createDice();

and it works... My question is, is there a way of avoiding creating an extra DICE variable to call all the methods? In other words I would like to call it like this:

import Dice from "./dice.js";

let dice1 = Dice.createDice();
let dice2 = Dice.createDice();

I've tried with IIFE but can't get it right.


Solution

  • In an IIFE you'd do

    export default (function () {
      function Dice() {
        this.createDice = function() { ... }
        ... 
      }
      return new Dice();
    })()

    But really, just do this

    function Dice() {
      this.createDice = function() { ... }
      ...
    }
    export default new Dice();