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

后端 未结 28 2446
长发绾君心
长发绾君心 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条回答
  •  时光说笑
    2020-11-27 14:49

    function add(x) {
        return function(y) {
            return x + y;
        };
    }
    

    Ah, the beauty of JavaScript

    This syntax is pretty neat as well

    function add(x) {
        return function(y) {
            if (typeof y !== 'undefined') {
                x = x + y;
                return arguments.callee;
            } else {
                return x;
            }
        };
    }
    add(1)(2)(3)(); //6
    add(1)(1)(1)(1)(1)(1)(); //6
    

提交回复
热议问题