Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript why wrap a variable or constructor in an IIFE?

I saw something like this today

var Visualizer = (function() {
    function Visualizer() {
    //...
    }
    Visualizer.prototype.function1 = function () { /* ... */ }
    //...
    return Visualizer;
})();

var viz = new Visualizer();

I don't understand the point of this versus just getting rid of the iife wrapper.

like image 478
natecraft1 Avatar asked Mar 28 '14 05:03

natecraft1


People also ask

When should we use IIFE in JavaScript?

Immediately-Invoked Function Expressions (IIFE), pronounced "iffy", are a common JavaScript pattern that executes a function instantly after it's defined. Developers primarily use this pattern to ensure variables are only accessible within the scope of the defined function.

Is IIFE obsolete?

Quite the contrary is true — the IIFE pattern is not obsolete at all! For this reason, I decided to write this follow-up post to showcase a variety of common use cases for immediately invoked function expressions.

What is the point of IIFE?

An Immediately-invoked Function Expression (IIFE for friends) is a way to execute functions immediately, as soon as they are created. IIFEs are very useful because they don't pollute the global object, and they are a simple way to isolate variables declarations.


1 Answers

There's no point for the specific construct that you show here. The reason to use an IIFE in this type of construct is when you have static data that you need to declare, want to be available to your object, but don't want it to be publicly accessible or interfere with the global namespace or be instance data.

Since the code you show doesn't show any of those, it isn't really offering any benefit as you've shown. But, if there were some other variables declared outside the object, but inside the IIFE, then the IIFE would protect and enclose them and isolate them from the outside world.

For example, if you had this:

Visualizer = (function() {
  var counter = 0;
  function Visualizer() {
    counter++;
    ...
  }
  Visualizer.prototype.getCount = function () { return counter; }
  ...
  return Visualizer;
})();

var viz = new Visualizer();

Then, the IIFE would be enclosing a variable counter that would be available to all methods of all instances of Visualizer, but isolated from the outside world and the IIFE would be offering some potential benefit.

like image 94
jfriend00 Avatar answered Oct 20 '22 21:10

jfriend00