本文介绍了将函数嵌套在彼此之间是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将函数嵌套在嵌套函数内的嵌套函数有什么缺点...

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

这是一个例子:

JS/jQuery:

JS/jQuery:

function one() {

    // do something

    function two() {

        // do something

        function three() {

            // do something

            function four() {

                // do something

            }

        }

    }
}

推荐答案

嵌套函数可以访问其父作用域,因此您可以从深度嵌套的函数中更改父作用域中的状态.例如

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;
}

这篇关于将函数嵌套在彼此之间是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:54