javascript - Should you ever use local inner functions? -


which of these seen better when writing javascript. foo, bar, , baz specific function won't 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 first is more efficient since if calling function more once other functions need created once. easier read main outer function 3 lines long , not longer.

the advantage can think second keeps these functions private outer function , not accessible rest of file since these functions not used anywhere else. making things public when shouldn't need bad less important in javascript situations this.

is possible choose differently depending on how function called or else?

  • if want functions publicly available 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 want auxiliary functions able access scope of main function, trade-of have recreated each time call main function, place auxiliary function inside main one

    var foobarbaz = function() { // public, created once   function foo() {} // private, created @ each foobarbaz call   function bar() {} // private, created @ each foobarbaz call   function baz() {} // private, created @ each foobarbaz call   foo(); bar(); baz(); }; 
  • if want keep auxiliary functions private, , don't want recreate them each time call main function, use 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();   }; })(); 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -