且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在javascript函数调用中实现任意链?

更新时间:2022-04-20 21:19:45

通常你会这样做:

var add = function(a,b){
    return a+b;
};

var sum = function(){
    return [].reduce.call(arguments, add);
}

然后你可以写:

sum(1,2,3,4); // 10

但是有可能破解你所追求的功能:

But it is possible to hack the functionality you're after:

var sum = function(x){
    var f = function(y){
        return sum(x+y);
    };
    f.valueOf = function(){
        return x;
    };
    return f;
};

sum(1)(2)(3)(4); // 10

请不要在生产代码中执行此操作!

Just don't do it in production code please!