How is a closure different from a callback?

前端 未结 9 972
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 19:08

I asked a question about callbacks and arrived at another question (see comment). How is a closure different from a callback?

相关标签:
9条回答
  • 2020-12-07 19:50

    closure :

    • A function keyword inside another function, you are creating a closure

    • Or A function return to an other function we can say closure

    Note Plain English : A little bit difference function passing as argument in another function is callback or if define in another function is closure

    var length = 101;
    function fn2() {
    	console.log("fffxxx: "+this.length);
    }
     
    var obj = {
      length: 5,
      method3: function(fn) {
        fn();
        arguments[0]();
      }
    };
     
    obj.method3(fn2, 1);
       
    **Outputहोगा

    fffxxx:101
    fffxxx:2**
    
    0 讨论(0)
  • 2020-12-07 19:53

    There's a good definition of closures here:

    A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

    In practice, that means it's a function that has some hidden variables.

    A callback is a higher-level idea. Generally it is a function which is passed around with the intent of being called at a later time. In JavaScript, closures are often used as callbacks.

    0 讨论(0)
  • 2020-12-07 19:57

    Check the introduction in this: http://jibbering.com/faq/faq_notes/closures.html. It can help you understand better how closures relate to functions.

    Here is a set of closure examples: http://www.javascriptkit.com/javatutors/closures2.shtml

    Basically, the callback is like a function pointer. The bit that makes it a closure, is when that function accesses anything on the context where it lives, like variables outside it. When that happens, the function will use the current values of the variables (as opposed to copy them). See example 4.

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