Closures: why are they so useful?

前端 未结 10 648
渐次进展
渐次进展 2020-12-07 10:04

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

相关标签:
10条回答
  • 2020-12-07 10:44

    For me, the biggest benefit of closures is when you're writing code that starts a task, leaves the task to run, and specifies what should happen when the task is done. Generally the code that runs at the end of the task needs access to the data that's available at the beginning, and closures make this easy.

    For example, a common use in JavaScript is to start an HTTP request. Whoever's starting it probably wants to control what happens when the response arrives. So you'll do something like this:

    function sendRequest() {
      var requestID = "123";
      $.ajax('/myUrl', {
        success: function(response) {
          alert("Request " + requestID + " returned");
        }
      });
    }
    

    Because of JavaScript's closures, the "requestID" variable is captured inside of the success function. This shows how you can write the request and response functions in the same place, and share variables between them. Without closures, you'd need to pass in requestID as an argument, or create an object containing requestID and the function.

    0 讨论(0)
  • 2020-12-07 10:45

    As to the concluding query: "Do (closures) fit in an OO world?"

    In many languages, closures, along with first-class functions, provide the very foundation for devising OO programs: Javascript, Lua and Perl come to mind.

    In another more "traditional" OO language with which I'm familiar, Java, there are 2 primary differences:

    1. Functions are not first class constructs
    2. In Java the implementation details of OO (whether closures are used internally) is not exposed directly to the developer as it is in Javascript, Lua and Perl

    Therefore in a "traditional OO" language such as Java, the addition of closures is largely just so much syntactic sugar.

    0 讨论(0)
  • 2020-12-07 10:52

    Maybe in the world of compiled programming the benefits of closures are less noticeable. In JavaScript closures are incredibly powerful. This is for two reasons:

    1) JavaScript is an interpreted language, so instruction efficiency and namespace conservation are incredibly important for faster and more responsive execution from large programs or programs that evaluate large amounts of input.

    2) JavaScript is a lambda language. This means in JavaScript functions are first class objects that define scope and scope from a parent function is accessible to child objects. This is important since a variable can be declared in a parent function, used in a child function, and retain value even after the child function returns. That means a variable can be reused by a function many times with a value already defined by the last iteration of that function.

    As a result closures are incredibly powerful and provide superior efficiency in JavaScript.

    0 讨论(0)
  • 2020-12-07 10:54

    IMHO it comes down to being able to capture blocks of code and their context to be referenced at some point later on and executed when/if/as required.

    They may not seem to be a big deal, and closures definitely aren't something you need to get things done on a daily basis - but they can make code code much simpler and cleaner to write/manage.

    [edit - code sample based on the comment above]

    Java:

    List<Integer> numbers = ...;
    List<Integer> positives = new LinkedList<Integer>();
    for (Integer number : integers) {
        if (number >= 0) {
            positives.add(number);
        }
    }
    

    Scala (skipping some of the other niceties like type inference and wildcards so we're only comparing the effect of the closure):

    val numbers:List[Int] = ...
    val positives:List[Int] = numbers.filter(i:Int => i >= 0)
    
    0 讨论(0)
提交回复
热议问题