闭包多板调用函数im javascript

Closure multiplate call function im javascript

本文关键字:im javascript 函数 调用 闭包      更新时间:2023-09-26

示例i记下

myFunc('asdas')

这是控制台。记录我

'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;
    }
}

如何正确实现此功能?

好吧,这有点有趣,但有效:

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)

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

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();