JavaScript - How do I learn about “closures” usage?

前端 未结 3 433
说谎
说谎 2021-02-03 16:09

From Wikipedia, the free encyclopedia: Closure (computer science)

In computer science, a closure is a function that is evaluated in an

相关标签:
3条回答
  • 2021-02-03 16:28

    (using an example from jQuery)

    function SetClassOnHover(className){
      $("td").hover(
        function () {
          $(this).addClass(className);
        },
        function () {
          $(this).removeClass(className);
        }
      );
    }
    

    The closure comes into play when the variable className is used inside the scope of each function. When SetClassOnHover exits, both functions must retain a handle on className in order to access its value when the functions are called. That's what the closure enables.

    0 讨论(0)
  • 2021-02-03 16:32

    A practical example of closures is when they are used to create "Private" variables, like

    function incrementer(){
        var i=0;
        this.increment=function(){
            i++;
        }
        this.get=function(){
            return i;
        }
    }
    

    The only way to access i is to use the method get, and the only way to change it is to use the method increment. In classes, you can do this to emulate private variables.

    0 讨论(0)
  • 2021-02-03 16:42

    Searching for "javascript closures" gave plenty of encouraging-looking links. The top three were these two (the third link was a reformatted version of the second):

    • Javascript closures
    • JavaScript closures for dummies

    If these didn't help you, please explain why so we're in a better position to actually help. If you didn't search before asking the question, well - please do so next time :)

    0 讨论(0)
提交回复
热议问题