Javascript中带有双括号的函数调用

Function calling in Javascript with double brackets

本文关键字:函数调用 Javascript      更新时间:2023-09-26

当我用双括号调用函数hi()()时,函数显示hi输出,它还会给出错误,说hi不是函数。

<html>
    <head></head>
<script>
function hello()
{
    document.write("hello");
}
function hi()
{
    document.write("hi");
    return "hello";
}
hi()();
</script>
</html>

()()与函数名称一起使用是什么意思?

如果hi返回一个函数而不是它的名字,双括号会很有用,如

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

这可能就是意图。

()放在计算结果为函数的内容之后将调用该函数。因此,hi()调用函数hi。假设hi返回一个函数,那么hi()()将调用该函数。例:

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"

如果hi()不返回函数,则hi()()将产生错误,类似于键入"not a function"();1232();之类的内容。

)()表示调用一个函数,如果返回另一个函数,则第二个括号将调用它。请在以下示例中找到:

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

添加(3)(4)

输出: 7

在上面的情况下,add(4) 将被调用用于添加函数,add(3) 将被调用为返回的函数。 此处参数 x 的值为 3,参数 y 为 4。

请注意:我们使用括号进行函数调用。

此函数的返回值是一个字符串,它不是可调用的对象。

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

但是如果你想多次调用这个函数,你可以使用 for 循环或其他一些东西。

hi()() 的例子:

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

JS小提琴:这里

如果您想在hi之后立即调用hello函数,请尝试以下操作:

 function hi()
    {
        document.write("hi");
        return hello; //<-- no quote needed
        // In this context hello is function object not a string
    }
你可以

使用eval()来执行它,即使它是字符串:eval(hi()+'()');