Question

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 }
Was it helpful?

Solution

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

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