用双括号在Javascript中调用函数
当我调用带有双括号的函数用双括号在Javascript中调用函数,javascript,Javascript,当我调用带有双括号的函数hi()()时,该函数显示hi输出,它还将给出错误提示,hi不是函数 <html> <head></head> <script> function hello() { document.write("hello"); } function hi() { document.write("hi"); return "hello"; } hi()(); </script> </h
hi()()
时,该函数显示hi
输出,它还将给出错误提示,hi
不是函数
<html>
<head></head>
<script>
function hello()
{
document.write("hello");
}
function hi()
{
document.write("hi");
return "hello";
}
hi()();
</script>
</html>
函数hello()
{
写下“你好”;
}
函数hi()
{
文件。填写(“hi”);
回复“你好”;
}
嗨()();
将
()
与函数名一起使用有什么意义?如果hi
返回的是函数而不是其名称,则双括号会很有用,如中所示
function hi(){
return hello;
}
hi()();
这可能就是我们的意图。此函数的返回值是一个字符串,它不是一个可调用的对象
function hi()
{
document.write("hi");
return "hello"; // <-- returned value
}
JS小提琴:
如果要在hi
之后立即调用hello
函数,请尝试以下操作:
function hi()
{
document.write("hi");
return hello; //<-- no quote needed
// In this context hello is function object not a string
}
函数hi()
{
文件。填写(“hi”);
return hello;//将()
放在某个计算结果为函数的内容之后将调用该函数。因此,hi()
调用该函数hi
。假设hi
返回一个函数,则hi()
将调用该函数。
例如:
如果hi()
不返回函数,那么hi()
将产生一个错误,类似于键入类似“nota function”();
或1232();
的内容,您可以使用eval()
执行它,即使它是字符串:eval(hi()+);
()表示调用一个函数,如果返回另一个函数,则第二个括号将调用该函数。请查找以下示例:
function add(x){
return function(y){
return x+y;
}
}
加(3)(4)
产出:7
在上述情况下,add函数将调用add(4),返回函数将调用add(3)。这里参数x的值为3,参数y的值为4
请注意:函数调用使用括号。或窗口[hi()]();
:P@Oleg是的,但这并不能使它变得更好。做同样事情的一种不那么邪恶的方式是window[hi()]()
我们可以用同样的方式使用rest参数执行动态参数。我的意思是添加(3)(4)或添加(3)(4)(5)或者我们添加的任何数量的括号都应该执行添加操作。如何实现此操作?请编辑标题以指定您的问题是关于双括号,而不是双括号。
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"
function add(x){
return function(y){
return x+y;
}
}