本文介绍了如何理解 JavaScript 中的蹦床?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

function repeat(operation, num) {
  return function() {
    if (num <= 0) return
    operation()
    return repeat(operation, --num)
  }
}

function trampoline(fn) {
  while(fn && typeof fn === 'function') {
    fn = fn()
  }
}

module.exports = function(operation, num) {
  trampoline(function() {
    return repeat(operation, num)
  })
}

我读过trampoline是用来处理溢出问题的,所以函数不会一直调用自己和堆栈.

I have read that the trampoline is used to deal with overflow problem, so the function would not just keep call itself and the stack up.

但是这个片段是如何运作的呢?尤其是trampoline 功能?while 究竟做了什么,它是如何实现目标的?

But how does this snippet function? Especially the trampoline function? What did it exactly do by while and how did it accomplish its goal?

感谢您的帮助:)

推荐答案

while 循环将一直运行,直到条件为假.

The while loop will keep running until the condition is falsy.

fn &&如果 fn 本身是假的,或者 fn 不是函数,那么 typeof fn === 'function' 将是假的.

fn && typeof fn === 'function' will be falsy either if fn itself is falsy, or if fn is anything other than a function.

前半部分实际上是多余的,因为假值也不是函数.

The first half is actually redundant, since falsy values are also not functions.

这篇关于如何理解 JavaScript 中的蹦床?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 09:05