Javascript 我不明白为什么这会给我一个打字错误

Javascript 我不明白为什么这会给我一个打字错误,javascript,Javascript,我编写了一个函数,希望参数与空格连接: 函数sayIt(str){ var stringCollection=[]; this.addToCollection=函数(str){ stringCollection.push(str); 调用中()部分的if(!str){// 返回stringCollection.join(“”); } }; 返回此.addToCollection(str); } log(sayIt('my')('name')('is')('Harry')());//应该记录“我

我编写了一个函数,希望参数与空格连接:

函数sayIt(str){
var stringCollection=[];
this.addToCollection=函数(str){
stringCollection.push(str);
调用中()部分的if(!str){//
返回stringCollection.join(“”);
}
};
返回此.addToCollection(str);
}

log(sayIt('my')('name')('is')('Harry')());//应该记录“我的名字是Harry”
当你有一个单词作为参数时,你没有返回一个函数——试试这个

函数sayIt(str){
var stringCollection=[];
函数concat(str){
stringCollection.push(str);
调用中()部分的if(!str){//
返回stringCollection.join(“”);
}
返回concat;
};
返回concat(str);
}

警惕(sayIt('my')('name')('is')('Harry'));//应该记录“我的名字是Harry”
我不太喜欢你的方法的设计,因为它对我来说很脆弱,但我相信你有一个理由支持它

修改

this.addToCollection = function(str){
    stringCollection.push(str);

    if(!str){  // for the () part in the call
        return stringCollection.join(" ");
    }
};


sayIt
不返回函数,因此您不能使用
sayIt(…)(…)
为什么您希望它工作?@Phil我现在添加了返回。还是一样。@RahulDesai仍然没有返回函数为什么它对你来说很脆弱?另外,为什么闭包函数返回相同的函数而没有任何参数,而外部函数返回相同的函数呢?@RahulDesai,首先,这纯粹是一个观点问题,因此没有对错之分。post中的更改纯粹是根据您实际部署它的方式提出的。请看一个链接示例,例如下划线JS——典型链接中的最后一个调用是返回累积结果的value()方法。HTHI了解为什么我们需要
返回concat(str)但不
返回concat。你能详细说明一下吗?为什么不像
return concat()
return concat
返回一个函数指针,因此您可以链接调用allong,就像在
sayIt('my')('name')('is')('Harry')()
中,其中
sayIt('my')
返回一个函数指针,
('name')
对其执行操作。。。等
this.addToCollection = function(str){
    stringCollection.push(str);

    if(!str){  // for the () part in the call
        return stringCollection.join(" ");
    }
    return this.addToCollection;
};