Closures: why are they so useful?

前端 未结 10 686
渐次进展
渐次进展 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:31

    It's a pity, people no longer learn Smalltalk in edu; there, closures are used for control structures, callbacks, collection enumeration, exception handling and more. For a nice little example, here is a worker queue action handler thread (in Smalltalk):

    |actionQueue|
    
    actionQueue := SharedQueue new.
    [
        [
            |a|
    
            a := actionQueue next.
            a value.
        ] loop
    ] fork.
    
    actionQueue add: [ Stdout show: 1000 factorial ].
    

    and, for those who cannot read Smalltalk, the same in JavaScript syntax:

    var actionQueue;
    
    actionQueue = new SharedQueue;
    function () {
        for (;;) {
            var a;
    
            a = actionQueue.next();
            a();
        };
    }.fork();
    
    actionQueue.add( function () { Stdout.show( 1000.factorial()); });
    

    (well, as you see: syntax helps in reading the code)

    Edit: notice how actionQueue is referenced from inside the blocks, which works even for the forked thread-block. Thats what makes closures so easy to use.

提交回复
热议问题