function createMessage() { var string = ''; var str; console.log('начальное значение аргумента: ' + str); return function callback(){ str = arguments[0]; console.log('значение аргумента в callback: ' + str); if (str !== undefined){ string += str; console.log('значение string в callback: ' + string); return callback(); } return string; } //console.log('вызов callback: ' + callback()); return string; } 
 console.log(createMessage("Hello")("World!")("how")("are")("you?")());// должно возвратить "Hello World! how are you? 

In my case, it loops on the first argument "Hello", the argument does not change

  • It does not get stuck Uncaught TypeError: createMessage(...)(...) is not a function : Uncaught TypeError: createMessage(...)(...) is not a function , which is generally logical. createMessage("Hello" /* argument is ignored */)("World!" /* returns "World!" */)/* not a function */("how")... - Qwertiy

1 answer 1

 function createMessage(st) { var string = st || ''; var str; return function callback(){ str = arguments[0]; if (str !== undefined){ string += str; return callback; } return string; } } var t = createMessage('hello'); t('hello')('word')() 

Try this. The essence of the closure is not to return the result of callback (), but the callback function.

Updated

In general, all this can be simplified

 function createMessage(st) { var string = st ||''; return function callback(){ string += arguments[0] || '' ; return arguments[0] ? callback : string; } } var test = createMessage('hello ')('word, ')('everybody')(); alert(test); 

  • you, like the author of the question, get the wrong sequence, skip the first call to createMessage("Hello") - Grundy
  • Yes, thanks, propravil - Kostiantyn Okhotnyk
  • Thanks friends. - Vitalik Mileshko