What is a 'Closure'?

前端 未结 23 1207
星月不相逢
星月不相逢 2020-11-22 08:02

I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?

23条回答
  •  无人及你
    2020-11-22 09:07

    Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.

    Function.prototype.delay = function(ms /*[, arg...]*/) {
      var fn = this,
          args = Array.prototype.slice.call(arguments, 1);
    
      return window.setTimeout(function() {
          return fn.apply(fn, args);
      }, ms);
    };
    

    And here's how you would use it:

    var startPlayback = function(track) {
      Player.play(track);  
    };
    startPlayback(someTrack);
    

    Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:

    startPlayback.delay(5000, someTrack);
    // Keep going, do other things
    

    When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
    This is a type of currying, or function decoration.

    Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.

提交回复
热议问题