6

I'm trying to build a game and I noticed that for organization it might be better to place some functions inside other functions because they are used in the original function exclusively. For example:

function fn1()
{
    fn2();

    function fn2()
    {
        //Stuff happens here
    }
}

fn1 gets called many times, and fn1 will call fn2 several times in its execution. When fn1 is called, does fn2 have to be re-processed (for lack of a better word) every time? Am I losing out in terms of performance because of this? Should I place fn2 after fn1 instead, like this?

function fn1()
{
    fn2();
}

function fn2()
{
    //Stuff happens here
}

1 Answer 1

2

You can do this to achieve similar scoping, but only create one copy of fn2:

//Initiliaze before you call `fn1`:  
var fn1 = (function(){

    // This is the function assigned to fn1
    return function(){
        fn2();
    }

    function fn2()
    {
        //Stuff happens here
    }
})();

Compare the console output of these to fiddles, the former of which creates an extra copy of fn2, since a locally scoped fn2 is created for each call to fn1: http://jsfiddle.net/A2UvC/3/ and http://jsfiddle.net/A2UvC/3/

There are advantages to the additional copys of fn2 however. They may have access to different variables like in the following situation:

function fn1(x){

    // Return an object exposing fn2 to the caller's scope
    return {fn2: fn2};

    // Each call to fn1 creates a new fn2 which has access 
    // to the closured `x` from the call to fn1 that created it
    function fn2(){
        console.log(x);
    }

}

var ex1 = fn1(1);
var ex2 = fn1(2);

ex1.fn2 == ex1.fn2; // true
ex1.fn2 == ex2.fn2; // false, because they are two distinct copies

ex1.fn2(); // 1
ex2.fn2(); // 2
ex2.fn2(); // 2
ex1.fn2(); // 1
Sign up to request clarification or add additional context in comments.

4 Comments

Since you are not enclosing the function expression in parenthesis, maybe you want to explicitly point out that you are calling the outer function immediately. Relevant reading material: benalman.com/news/2010/11/….
@FelixKling I added the parenthesis to make that more obvious.
+1 :-) Also, can you explain if the OP's 1st way creates multiple copies of fn2
I've been looking this over because I don't think I fully understand this correctly. In your first example, you're creating a function that returns a function, so that it can be 'injected' into any other function, correct? As for your second example, given that fn2 will be accessed exclusively by fn1, why not just define fn2 inside fn1 if I'm going to be making multiple copies anyway? Also, both those fiddles link to the same thing.

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.