2

I've just come accross this code and wondered what the benefit is of storing the properties that they are actually using inside a function.

var FormEditable =  function() {
    return{
        init: function() {
        console.log('test');
        }
    }
}();
 jQuery(document).ready(function() {
 FormEditable.init()
});

As opposed to...

var FormEditable =  function() {
    return{
        init: function() {
        console.log('test');
        }
    }
};
 jQuery(document).ready(function() {
 FormEditable().init()
});

or...

var FormEditable =  {
    init: function() {
        console.log('test');
    }
};
 jQuery(document).ready(function() {
 FormEditable.init()
});

The last example is what I am probably more familiar with seeing. All three work I just wondered why go for the first?

jhodgson4
  • 1,566
  • 3
  • 20
  • 35
  • revealing module pattern. – epascarello Dec 08 '15 at 13:13
  • 1
    I don't think this is a duplicate of the answer mentioned, the code here is doing 3 different things. 1 and 3 are pretty much identical, you're ending up with FormEditable pointing to an object with an init function member. In 1 you are using an IIFE (Immeditately-Invoked Function Expression) whereas 3 is a direct assignment to the object. In 2 you are getting a reference to a function, not an object. Hence you have to invoke the function to get the object to call init on. IIFE's are generally used in the revealing module pattern to provide data encapsulation away from the global namespace. – Daniel Cook Dec 08 '15 at 13:19
  • 1
    the first one has a syntax error should be `var FormEditable = (function(){ return { init: function(){ console.log('init') } } })();` function should be wrapped in parens to make it an expression that can be executed. – synthet1c Dec 08 '15 at 13:22
  • Thanks @DanielCook I think that explains what I was looking for.. If the first is immediately invoked, why would they still use the document.ready portion? – jhodgson4 Dec 08 '15 at 15:34

0 Answers0