Question

I know what an IIFE is and that its purpose is to provide some form of encapsulation. The last few days I have been watching a video tutorial in which they use this pattern:

var ViewModel = (function(){
  var model = function(){
    //...
  };
  return model;
})();

//in the same or another file:
var viewModel = new ViewModel();

I don't see the advantage of using an IIFE here. What is the advantage over doing this:

var ViewModel = function(){ 
    //...
  return model;
};

var viewModel = new ViewModel();
Was it helpful?

Solution

In this particular case, there is no advantage.

In a more general case, it allows the creation of scoped variables for the use of the function(s) that are returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top