Closures: why are they so useful?

前端 未结 10 646
渐次进展
渐次进展 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.

提交回复
热议问题