简体   繁体   English

JS递归函数调用

[英]JS Recursive function call

If I call the function once like this 如果我这样调用once函数

var button = document.querySelector('button');

button.addEventListener('click', once);

function once() {
  console.log('one');

  button.removeEventListener('click', once);
}

It's calling only once. 它只打电话一次。

But if I called like this once() 但是如果我这样打过once()

var button = document.querySelector('button');

button.addEventListener('click', once());

function once() {
  console.log('one');

  button.removeEventListener('click', once());
}

Exception throws 异常抛出

Exception: InternalError: too much recursion 异常:InternalError:过多的递归

Could you please explain why this is happening. 您能否解释一下为什么会这样。

() after function name invoke's the function. ()在函数名称调用后的功能。 So as button.addEventListener('click', once()); 因此就像button.addEventListener('click', once()); you are bind the return value of once() method which is undefined. 您绑定的once()方法的返回值是未定义的。

And since once() is called recursively without any break statement, you are getting the InternalError: too much recursion . 而且由于once()在没有任何break语句的情况下被递归调用,因此您将获得InternalError:过多的递归

You should pass the function reference. 您应该传递函数引用。

button.addEventListener('click', once); 

For Additional Info: 有关其他信息:

Pointer Vs Delegates 指针与代表

If you put () after the name of a variable holding a function, then you call the function . 如果将()放在包含函数的变量的名称之后,则调用函数

If a function calls itself, then it will get called, call itself, call itself again and so on unto infinity. 如果一个函数调用了自己,那么它将被调用,调用自己,再次调用自己,依此类推直至无限。 This is recursion. 这是递归。 Doing something unto infinity will cause a computer to run out of memory, so it is undesirable. 进行无穷大操作将导致计算机内存不足,因此这是不可取的。

JavaScript engines prevent this by throwing an exception when you try it. JavaScript引擎通过在尝试时抛出异常来防止这种情况。

(There are exceptions, of course, a function that calls itself conditionally can be very useful ). (当然也有例外, 有条件地调用自身的函数可能非常有用 )。

The first code is correct, because you register the function to be called. 第一个代码正确,因为您注册了要调用的函数。

The second code tries to register the result of the function call once() . 第二段代码尝试注册once()函数调用once()的结果。 This means you actually execute the function when you only want to register it. 这意味着您实际上只想注册该功能。 Now, in your function body, you do the same to deregister the callback. 现在,在函数主体中,执行相同的操作以注销回调。 Here again, you call the function you are already executing and hence, you recurse infinitely. 在这里,您再次调用已经执行的函数,因此可以无限递归。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM