简体   繁体   English

闭包和funarg问题之间的区别?

[英]Difference between a closure and the funarg problen?

I have a miss understanding, is the strainer function an example the downward funarg problem? 我错过了一个了解,滤网功能是向下的funarg问题的一个例子吗? I was using the chrome debugger under the sources panel and noticed this under the scope section. 我在“源代码”面板下使用了chrome调试器,并在“作用域”部分注意到了这一点。

我的描述的屏幕截图

Is the strainer function param cb a closure or is the function strainer the closure? 过滤器功能参数cb是闭包还是功能strainer闭包? I'm finding it difficult to sort through the information about closures and the funarg problem on the web. 我发现很难对有关闭包和funarg问题的信息进行排序。 I clearly don't understand the funarg problem or closures and need some help? 我显然不了解funarg问题或闭包,需要帮助吗?

function strainer(collection, cb) {
  return collection.reduce(function inner(acc, curr) {
    if (cb(curr)) {
      return acc.concat(curr);
    }
    return acc;
  }, []);
}

function even(number) {
  if (number % 2 === 0) {
    return true;
  }
  return false;
}

var collection = [1, 2, 3, 4, 5];

strainer(collection, even);

Background: I was under the impression private variables returned to an outer environment created closures but the example looks like something different. 背景:我给人的印象是,将私有变量返回到外部环境后创建了闭包,但该示例看起来有些不同。

The flintstones function example below has closure over the scope of the quotes function.(I think this is the upward funarg problem) 下面的打火石函数示例对quotes函数的范围进行了封闭(我认为这是向上的funarg问题)

 function quotes() { var x = 'yabba dabba doo!'; return function flintstones() { return x; } } var fredSays = quotes(); fredSays(); 

Is the strainer function param cb a closure or is the function strainer the closure? 过滤器功能参数cb是闭包还是功能strainer闭包?

Neither, actually. 两者都不是。 inner is the closure. inner是封闭。 You are inspecting the scope chain of inner here - it has local acc and curr variables, and free variable cb that closed over the cb variable from the strainer scope. 您正在此处检查inner的作用域链-它具有本地acccurr变量,以及在strainer作用域内封闭cb变量的自由变量cb That's what the debugger is trying to show you. 这就是调试器试图向您显示的内容。 The cb part of the strainer scope is not allocated on the stack but in the heap, however the debugger doesn't display that detail. strainer范围的cb部分未分配在堆栈上,而是分配在堆中,但是调试器不会显示该详细信息。

Yes, this is more or less the downward funarg problem . 是的,这或多或少是向下的funarg问题 inner is passed to reduce here, and that's why we create a closure for it. inner传递到这里来reduce ,这就是为什么我们为此创建一个闭合。 Notice that the distinction between upward and downward is meaningless in JS, since we never know what the called function does with the passed callback - it might as well stow it away somewhere. 注意,在JS中,向上和向下之间的区别是没有意义的,因为我们永远不知道被调用函数对传递的回调有何作用-最好将其存放在某个地方。 Proving that it stays contained in and does not escape the call is not done. 证明它仍然包含在其中并且不会逃避调用的情况尚未完成。

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

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