2

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.

Ben Quan
  • 773
  • 11
  • 25

1 Answers1

10

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();
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87