How can I make var a = add(2)(3); //5 work?

后端 未结 28 2450
长发绾君心
长发绾君心 2020-11-27 14:11

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I\

28条回答
  •  旧时难觅i
    2020-11-27 14:51

    Concept of CLOSURES can be used in this case.
    The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).

    function add(a){
    
        return function(b){
            console.log(a + b);
        }
    
    }
    
    
    add(2)(3);
    

    Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp

提交回复
热议问题