javascript - 参数对应: callback vs.闭包(?)

标签 javascript parameters callback nested closures

对于 javascript 闭包和回调,我对为什么命名嵌套函数采用的参数与闭包参数不同(从外部函数继承?)的区别感到困惑。例如:

var filter = function (collection, test) {
    var newArray = [];
    each(collection, function (value) {
        if (test(value)) { 
            newArray.push(value);
        }
    });
    return newArray;
};

过滤器函数对每个函数进行操作。 (每个)“value”参数对应什么输入?回调函数的参数是否会自动与过滤器的第一个参数对齐,因为它们都是各自函数的第一个参数?如果外部函数和内部函数都接受另一个参数,那么它们也会因为它们的位置而排列吗?这里的内部/外部函数之间的参数关系似乎与闭包的参数不同(闭包似乎接受一个新参数;它的参数与外部函数的参数不一致)例如:

var outer = function(par1, par2) {
    var hold = par1 + par2;

    function inner(par3) {
       return par3 + par1 + par2;
    }
    return inner;
};

var closure = outer (5,4);

closure(2);

我看到内部函数是从外部函数返回的(当存储在另一个变量中时),并且其自己的参数与外部函数分开。

命名/建立的函数是否从其封闭函数继承其参数对应关系?

回调函数是否采用自己的参数(与其封闭函数分开),因为它们从该函数返回并保存到变量中?

最佳答案

What input does the "value" parameter (in each) correspond to?

这取决于每个的作用。它不是标准的 JS 全局变量,而且您还没有分享您对它的定义。

Does a callback function's parameter automatically line up with filter's first parameter because they are both the first parameter of their respective functions?

没有。传递给任何函数的参数都取决于调用该函数的代码。

If the outer function and the inner one both accepted another parameter, would those line up because of their position as well?

没有。

Do named/established functions inherit their parameter correspondence from their enclosing functions?

没有。

Do callback functions take on their own parameter - separate from their enclosing function

是的

because they are returned out of that function and saved to a variable?

没有。这是因为它们是函数。

function outer(foo, bar) {
  console.log("Outer gets foo " + foo + " because foo is a argument of outer");

  console.log("Outer gets bar " + bar + " because foo is a argument of outer");

  return inner;


  function inner(baz) {
    console.log("Inner gets foo " + foo + " because foo is a variable still in scope");
    console.log("Inner gets bar " + bar + " because bar is a variable still in scope");
    console.log("Inner gets baz " + baz + " because baz is an argument of inner");
  }

}

var returned_inner = outer(1, 2);
returned_inner(3);

<小时/>

With javascript closures and callbacks, I am confused on the difference between why the parameters that a named, nested function take are different (inherited from the outer function?) than a closure's parameters.

您的困惑问题源于一个简单的事实,即大多数时候,当您使用回调时,实际调用它的函数是由其他人编写的,而您从不查看就在这儿。

关于javascript - 参数对应: callback vs.闭包(?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34385538/

相关文章:

javascript - 我有 9 个小图像,单击这些图像时,它们会在较大版本的图像中淡出。为什么在浏览器中不起作用(FF))

javascript - 嵌套订阅并需要所有值作为正文传递给 API - Angular 6 RxJS

mysql - 在 powershell 中将参数传递给 mysql.exe

javascript - 如何调用一个函数,其名称在 Json 对象中传递?

jquery - 向插件添加回调和触发事件

javascript - 使 jQuery UI 可拖动到窗口外

javascript - JQuery Onclick 从 span 获取值并将其添加到输入值

c# - 如何从类中返回多个参数

mysql存储过程输入参数值

javascript - 如何在嵌套方法定义中引用对象数据结构?