函数附加在不同类型的调用中

时间:2014-10-09 06:10:03

标签: javascript jquery

我想创建一个附加参数值的函数。重要的是它应该接受下面给出的函数调用

concat('hello', 'world');
concat('hello')('world');

这两个都应该返回" helloworld"。怎么可能?

4 个答案:

答案 0 :(得分:3)

这适用于问题中的规范,加上一点额外的内容:

function concat(/* varargs */) {
    // Called with multiple arguments: concatenate them immediately
    var originalArgs = [].slice.call(arguments);
    if (originalArgs.length > 1) {
        return originalArgs.join("");
    }

    // Called with zero or one arg: return a function that will perform the concatenation later
    return function(/* varargs */) {
        var newArgs = [].slice.call(arguments);
        var combinedArgs = originalArgs.concat(newArgs);
        return concat.apply(null, combinedArgs);
    }
}

concat('a', 'b'); // 'ab'
concat('a')('b'); // 'ab'
concat('a', 'b', 'c'); // 'abc'
concat('a')('b', 'c'); // 'abc'

也就是说,它不会延伸过两次调用(而且我认为不可能创建一个能够实现的功能)并且它会过度使用。我会认真考虑你是否需要这个功能。

答案 1 :(得分:1)

function concat(a,b){
    if (arguments.length == 1) {
        return function(c){return a+c;};
    } else if (arguments.length == 2) {
        return a+b;
    }
}

答案 2 :(得分:0)

您可以使用+运算符来连接字符串。除非有特定用途,否则真的不需要任何特殊功能。

例如:

var string = 'hello, ' + 'world' + '!!!'

答案 3 :(得分:0)

又一种方式

function concat(){
    var args = Array.prototype.slice.call(arguments).reduce(function(a,b){return a.concat(b)},[]),
        internal = concat.bind(this,args);

    internal.toString = function(){return args.join('');}
    return internal
}

使用

console.log(concat('hello', 'world')) //helloworld
console.log(concat('hello')('world')) // helloworld
console.log(concat('hello')('world','!!!')) //helloworld!!!
console.log(concat('hello')('world')('!!!')) //helloworld!!! 
相关问题