JavaScript functionCall(arg1)(arg2)

2019-09-11 01:43发布

I'm learning JavaScript and I found this example

say("Hello")("World"); 

This code should return "Hello World".

I don't know how to implement this even what keyword type to google to find soulution. Can you advice me please what is name of this pattern or how it is possible to implement it in JavaScript?

标签: javascript
2条回答
爷、活的狠高调
2楼-- · 2019-09-11 02:11

You could do:

function say(firstword){
    return function(secondword){
     return firstword + " " + secondword;   
    }
}

http://jsfiddle.net/o5o0f511/


You would never do this in practice though. I'm sure this is just to teach you how functions can return executable functions.

There's some more examples of this pattern here:

How do JavaScript closures work?

查看更多
Root(大扎)
3楼-- · 2019-09-11 02:15

Possibly you can try closures:

var say = function(a) {//<-- a, "Hello"
  return function(b) {//<-- b, "World"
    return a + " " + b;
  };
};

alert(say("Hello")("World")); //<--  "Hello World"

Here, when say("Hello") is invoked it returns the inner block. The later call with ("World") invokes the inner block returning the concatenated string "Hello World"

查看更多
登录 后发表回答