在javascript中关闭多板调用函数

时间:2014-09-19 10:32:53

标签: javascript

示例我写下

myFunc('asdas')

这是console.log me

'asdas'

然后我写下

myFunc('as')('ds')('ko')....('other')

功能必须是console.log me

  

“as ds ko .... other”

我尝试了解这一点,但有很多问题。

function me (str){
    //var temp = str;
    return function mes(val) {
        val += ' '+ str;
        console.log(val);
        //return mes;
    }
}

如何正确实现此功能?

2 个答案:

答案 0 :(得分:2)

嗯,这有点好笑,但有效:



concat = function(x, val) {
    val = (val || "") + x;
    var p = function(y) { return concat(y, val) };
    p.toString = function() { return val };
    return p
}

x = concat('a')('b')('c')('d');
document.write(x)




答案 1 :(得分:0)

您可以生成多个控制台日志并将其链接如下:

function me(str) {
    console.log(str);
    return me; // or whatever you called the function
}

me(1)(2)(3);

据我所知,如果你只是链接,函数无法知道它何时应该输出。

我能想到的最佳选择是:

function me(str) {
    me.str = me.str || ''; // make sure me.str is set

    // set me.write if this is the first call to me()
    me.write = me.write || function() {
        console.log(me.str);
    }

    me.str += (me.str.length ? ' ' : '') + str; // add a space if needed
    return me; // or whatever you called the function
}

me(1)(2)(3).write();