سؤال

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();
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top