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()
    {
    }
}
1
  • 1
    there is no difference between the two other than what you mentioned Commented Jun 13, 2011 at 6:22

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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() {
    }
}

3 Comments

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: Actually, the two examples are entirely different. The first assigns the returned value, the second assigns the function itself.
...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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.