Is it bad practice to nest functions within each other? [closed]

人走茶凉 提交于 2021-02-05 07:21:26

问题


What are the disadvantages to nesting a function within a nested function within a nested function...

Here's an example:

JS/jQuery:

function one() {

    // do something

    function two() {

        // do something

        function three() {

            // do something

            function four() {

                // do something

            }

        }

    }
}

回答1:


One disadvantage of declaring a nested function is the fact that it will be created inside function's environment every time you call parent function.

In theory, this could decrease performance if parent function is called frequently.

But, nested function are very used in javascript.For example,closures are extremely powerful and should be understood by all JavaScript developers.

Read more about closures, here.




回答2:


Nested functions have access to their parent scope so you could change state in a parent's scope from a deeply nested function. For example

function one() {
  var a = 1;
  two(); // a = 4

  function two() {  
    var b = 2;
    three(); // b = 4

    function three() {
      var c = 3;
      four(); // c = 4

      function four() {
        a = 4;
        b = 4;
        c = 4;
      }
    }  
  }
}

On one hand this is pretty powerful. On the other hand it can easily get sloppy and hard to reason about because you have to make sure any child function hasn't changed a value in any of its parents.

If you stick to not nesting your functions you won't have to worry that the state inside your function is being changed from inside of a nested function.

function one() {
  var a = 1;
  two(); // a = 1
}

function two() {  
  var b = 2;
  three(); // b = 2
}

function three() {
  var c = 3;
  four(); // c = 3
}  

function four() {
  a = 4;
  b = 4;
  c = 4;
}


来源:https://stackoverflow.com/questions/41535428/is-it-bad-practice-to-nest-functions-within-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!