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

后端 未结 28 2359
长发绾君心
长发绾君心 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:52

    function add () {
        var args = Array.prototype.slice.call(arguments);
     
        var fn = function () {
            var arg_fn = Array.prototype.slice.call(arguments);
            return add.apply(null, args.concat(arg_fn));
        }
     
        fn.valueOf = function () {
            return args.reduce(function(a, b) {
                return a + b;
            })
        }
     
        return fn;
    }
    
    console.log(add(1));
    console.log(add(1)(2));
    console.log(add(1)(2)(5));

    from http://www.cnblogs.com/coco1s/p/6509141.html

提交回复
热议问题