为什么在将函数作为参数传递时必须省略括号? [英] Why do I have to omit parentheses when passing a function as an argument?

查看:56
本文介绍了为什么在将函数作为参数传递时必须省略括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚为什么以下代码在包含括号的情况下会导致堆栈溢出,而在省略括号时却不会导致堆栈溢出.

I am trying to wrap my head around as to why the following code results in a stack overflow when the parentheses are included, but do not when they omitted.

我将函数本身作为setTimeout的参数来调用,它可以在没有括号的情况下工作,但是当我添加它们时当然会失败.我的直觉是在函数后添加().只是希望有人可以帮我解决这个问题.教员什么时候是可选的而不是可选的?

I am calling the function itself as an argument to setTimeout and it works without parantheses, but of course fails when I add them. It was my intuition to add the () after the function. Just hope somebody can clear this up for me. When are parans optional and not?

情况1:

var a = 1;

function foo() {
    a++;
    document.write(a);
    setTimeout(foo(), 2000)
}​ 
// RangeError: Maximum call stack size exceeded

情况2:

var a = 1;

function foo() {
    a++;
    document.write(a);
    setTimeout(foo, 2000)
}​
// parens are omitted on foo function and it works. 

推荐答案

通常首先参考 setTimeout 来问这个问题,但我认为必须指出的是,这里的行为不是特定于该功能.您只需要了解括号的作用以及省略括号的含义.

This question is usually first asked in reference to setTimeout, but I think it's important to point out that the behavior here isn't specific to that function. You simply need to understand what the parenthesis do and what it means to leave them off.

承担以下功能:

function foo() {
    return 5;
}

请考虑以下两个变量声明/赋值:

Consider the following two variable declarations/assignments:

var one = foo();
var two = foo;

这些变量有什么值?

在第一种情况下,我们执行 foo 函数,并将其返回值(数字 5 )分配给一个.在第二种情况下,我们将 foo 本身(更确切地说是对 foo 的引用)分配给 two .该功能从不执行.

In the first case we're executing the foo function and assigning its return value -- the number 5 -- to one. In the second case we're assigning foo itself -- more precisely, a reference to foo -- to two. The function is never executed.

有了这些知识并了解到 setTimeout 希望将对函数的 reference 作为其第一个参数,很明显,第一种情况失败了,而第二种情况失败了有效.

With this knowledge and an understanding that setTimeout expects as its first argument a reference to a function, it should be obvious why your first case fails, but the second one works.

当然,您正在执行的功能是对自身的递归调用,这使您的问题更加恶化.这将永远运行-从某种意义上说是永久的-因为没有终止递归的基本情况.

Of course, your problem is exacerbated by the fact that the function you're executing is a recursive call to itself. This will just run forever -- for some definition of forever -- because there's no base case to terminate the recursion.

这篇关于为什么在将函数作为参数传递时必须省略括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆