Function calling in Javascript with double brackets

后端 未结 5 478
小蘑菇
小蘑菇 2021-02-06 13:23

When I call function hi()() with double brackets the function displays hi output and it will also give error saying, that hi is not functi

相关标签:
5条回答
  • 2021-02-06 13:37

    Putting () after something that evaluates to a function will call that function. So, hi() calls the function hi. Assuming hi returns a function then hi()() will call that function. Example:

    function hi(){
        return function(){return "hello there";};
    }
    
    var returnedFunc = hi();  // so returnedFunc equals function(){return "hello there";};
    var msg = hi()();         // so msg now has a value of "hello there"
    

    If hi() doesn't return a function, then hi()() will produce an error, similar to having typed something like "not a function"(); or 1232();.

    0 讨论(0)
  • 2021-02-06 13:37

    The return value of this function is a string which is not a callable object.

    function hi()
    {
        document.write("hi");
        return "hello"; // <-- returned value
    }
    

    But if you want to call this function multiple times you can use a for-loop or some things else.

    Example of hi()():

    function hi(){
        return function(){ // this anonymous function is a closure for hi function
           alert('some things')
        }
    }
    

    JS Fiddle: here

    If you want to call hello function immediately after hi try this:

     function hi()
        {
            document.write("hi");
            return hello; //<-- no quote needed
            // In this context hello is function object not a string
        }
    
    0 讨论(0)
  • 2021-02-06 13:38

    You can use eval() to execute it even if it's string : eval(hi()+'()');

    0 讨论(0)
  • 2021-02-06 13:52

    ()() means calling a function and if returns another function second parenthesis will call it.Please find below example :

    function add(x){
        return function(y){
            return x+y;
        }
    }
    

    add(3)(4)

    output: 7

    in above case add(4) will be called for add function and add(3) will be called for returned function. here value of parameter x is 3 and parameter y is 4.

    Please note : we use parenthesis for function call.

    0 讨论(0)
  • 2021-02-06 13:57

    The double parenthesis would have been useful if hi had returned a function instead of its name, like in

    function hi(){
        return hello;
    }
    hi()();
    

    That's probably what was the intent.

    0 讨论(0)
提交回复
热议问题