nCardot
nCardot

Reputation: 6585

Does the module pattern require the use of an IIFE?

In a Udacity lesson it says conflicting things about the module pattern:

The Module Pattern requires the use of IIFE's

and

At its core, the Module Pattern leverages scope, closures, and (commonly) IIFE's.

So, if I understand correctly, a module pattern requires the use of a closure, but does the closure need to be in an IIFE or not?

Upvotes: 1

Views: 1808

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51886

In JavaScript ECMAScript 5 and older, an IIFE, or immediately-invoked function expression, was necessary to create a function scope that prevented var declarations from polluting the global namespace when implementing the revealing module pattern.

(function () {
  var foo = 'bar'
  var counter = 0

  this.someGlobalModule = function () {
    counter++

    return { foo: foo, counter: counter }
  }
}.call(this))
// this === window at top-level in browser

// no access to function-scope foo or counter, only someGlobalModule()
var value = someGlobalModule()

// value.foo === 'bar'
// value.counter === 1

Now with JavaScript ECMAScript 6, the introduction of const and let declarations allow block-scope variables, as opposed to function-scope, so you can simply use a block-scope to implement the revealing module pattern:

{
  const foo = 'bar'
  let counter = 0

  // this === window at top-level in browser
  this.someGlobalModule = () => {
    counter++

    return { foo, counter }
  }
}

// no access to block-scope foo or counter, only someGlobalModule()
let value = someGlobalModule()

// value.foo === 'bar'
// value.counter === 1

Upvotes: 5

Related Questions