What are the benefits of a closure, and when are they typically used?

前端 未结 3 1825
攒了一身酷
攒了一身酷 2020-12-29 07:19

I\'m a web developer, but lots of folks are looking for slightly more advanced skills and understanding closures seems to be at the forefront of this.

I get the whol

3条回答
  •  天命终不由人
    2020-12-29 08:08

    They can be good for lots of things, for example, visibility (like private members in traditional OO).

    var count = function(num) {
    
       return function(add) {
           add = add || 1;
           num += add;
           return num;
       }
    
    }
    

    See it.

    My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).

    This is a pretty good overview.

    See also on Stack Overflow

    • What is a practical use for a closure in JavaScript?
    • How does a javascript closure work ?
    • When actually is a closure created?
    • more...

提交回复
热议问题