2

In the Module Pattern example from Addy Osmani, a private function is assigned to a variables as shown in this example:

var myNamespace = (function () {

  var myPrivateVar, myPrivateMethod;

  // A private counter variable
  myPrivateVar = 0;

  // A private function which logs any arguments
  myPrivateMethod = function( foo ) {
      console.log( foo );
  };

  return {

    // A public function utilizing privates
    myPublicFunction: function( bar ) {

      // Increment our private counter
      myPrivateVar++;

      // Call our private method using bar
      myPrivateMethod( bar );

    }
  };

})();

I would have simply written the private function as:

   function myPrivateMethod( foo ) {
      console.log( foo );
  };

Is there any reason to assign the function to a variable if it's not used as a delegate? I'm looking at some code that uses this pattern consistently and I'm finding it hard to follow. For example:

var _initializeContext = function() { // many lines of code }
Barmar
  • 741,623
  • 53
  • 500
  • 612
Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • 2
    [var functionName = function() {} vs function functionName() {}](http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname) may be able to answer this. The technical difference between the 2 forms is in whether the `function` or just the `var` is hoisted. But, being at the top of the scope already, it's mostly a stylistic choice. – Jonathan Lonowski Oct 08 '13 at 18:33
  • 1
    In this context, there's no significant difference between the two ways of writing the private function. It's just personal style. I don't see the syntax you mention in the section on the Revealing Module Pattern, it comes from the Module Pattern section. – Barmar Oct 08 '13 at 18:35
  • @Barmar You're right, I edited the title. – Jamie Ide Oct 08 '13 at 18:44

1 Answers1

2

This is a function declaration vs a function expression issue. To some degree it's a stylistic choice. What you do need to be aware of is that function declarations get hoisted by the JS interpreter, which function expressions aren't. Some people prefer to use function expressions because they don't like the idea of their code being rearranged.

You might want to check out:

var functionName = function() {} vs function functionName() {} http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/ http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

Community
  • 1
  • 1
LiavK
  • 702
  • 6
  • 20