简体   繁体   中英

Should you ever use local inner functions?

Which of these is normally seen as better when writing JavaScript. Foo, bar, and baz are specific to this function so won't be used anywhere else in other functions.

function() {
    foo();
    bar();
    baz();
}

function foo() {
    //lines of code
}

function bar() {
    //lines of code
}

function baz() {
    //lines of code
}

Or

function() {
    function foo() {
        //lines of code
    }
    foo();
    function bar() {
        //lines of code
    }
    bar();
    function baz() {
        //lines of code
    }
    baz();
}

The advantages of the first is it is more efficient since if you are calling the function more that once the other functions only need to be created once. It is also easier to read as the main outer function is now only 3 lines long and not much longer.

The only advantage I can think for the second is it keeps these functions private to the outer function and not accessible to the rest of the file which is good since these functions will not be used anywhere else. Obviously normally making things public when they shouldn't need to be is bad but is that less important in JavaScript situations like this.

Is it possible you would choose differently depending on how often the function was called or anything else?

  • If you want all functions to be publicly available by themselves, declare them separately

     function foo() {} // Public, created once function bar() {} // Public, created once function baz() {} // Public, created once var fooBarBaz = function() { // Public, created once foo(); bar(); baz(); }; 
  • If you want the auxiliary functions to be able to access the scope of the main function, with the trade-of that they will have to be recreated each time you call the main function, place the auxiliary function inside the main one

     var fooBarBaz = function() { // Public, created once function foo() {} // Private, created at each fooBarBaz call function bar() {} // Private, created at each fooBarBaz call function baz() {} // Private, created at each fooBarBaz call foo(); bar(); baz(); }; 
  • If you want to keep the auxiliary functions private, and you don't want to recreate them each time you call the main function, use an IIFE

     var fooBarBaz = (function() { // IIFE function foo() {} // Private, created once function bar() {} // Private, created once function baz() {} // Private, created once return function() { // Public, created once foo(); bar(); baz(); }; })(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM