0

When does it make sense to use function expressions instead of function declarations when implementing "private methods"? In both cases, the functions are encapsulated, the only practical difference appears to be that I wouldn't be able to call myFunc1 in the constructor. I know I should be using the prototype property either way, but I'm just curious.

function myClass
{
    myFunc1() //error
    myFunc2() //success

    var myFunc1 = function()
    {
    }

    function myFunc2()
    {
    }
}
Derg
  • 281
  • 3
  • 8
  • 1
    there is no difference between the two other than what you mentioned –  Jun 13 '11 at 06:22

2 Answers2

1

You can call the function assigned to a variable, but you have to assign it before you can call it:

function myClass() {

  var myFunc1 = function() {
  }

  myFunc1() //success
  myFunc2() //success

  function myFunc2() {
  }

}

Those functions are local to the constructor, so it's not the same as using the prototype. To make a public function you need to assign it to the object:

function myClass() {

  this.myPublicFunc1 = function() {
  }

  this.myPublicFunc2 = myFunc2;

  function myFunc2() {
  }

}

var o = new myClass();
o.myPublicFunc1() //success
o.myPublicFunc2() //success
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

You must use an expression if you want to invoke the function immediately.

This one invokes it and assigns the return value to the variable:

function myClass {

    var myVar = function() {
       return 'some value';  // <--- 2. assign the return value to the variable
    }();  // <--- 1. invoke the function immediately

    function myFunc2() {
    }
}

This one invokes it, but assigns the function itself to the variable:

function myClass {

    var myFunc1;

    (myFunc1 = function() {  // <--- 1. assign the function to the variable
       // Do something
    })();  // <--- 2. invoke the function immediately

    function myFunc2() {
    }
}
user113716
  • 318,772
  • 63
  • 451
  • 440
  • I don't think there is any practical difference in the two examples above. The first would be clearer with an extra set of parenthesis around the RHS expression, second is just convoluted. – RobG Jun 13 '11 at 06:37
  • @RobG: Actually, the two examples are entirely different. The first assigns the returned value, the second assigns the function itself. – user113716 Jun 13 '11 at 06:41
  • ...and yes, I'd agree that a set of parentheses would add clarity to the first, but they're not required. I don't find the second one to be convoluted. – user113716 Jun 13 '11 at 06:42