javascript - 外部函数 "store"如何获取内部函数的参数?

标签 javascript function

我在 Mozilla 开发者页面找到了这个示例,但无法理解这个概念。

   function outside(x) {
       function inside(y) {
          return x + y;
       }
       return inside;
    }
    fn_inside = outside(3); //returns inside(y) -- from firebug
    result = fn_inside(5); // returns 8

    result1 = outside(3)(5); // returns 8

看起来 3 有点存储在函数 ' inside 中' 在第二次调用期间将其与 5 相加并返回 8。

与第一次调用不同,第二次调用外部函数 ( outside(3)(5) ) 返回值 (8) 而不是内部函数 ( inside )?

最佳答案

It seems like 3 is somewhat stored in the function 'inside' and during the second call adds it with 5 and returned 8.

对。每次调用 outside 都会创建一个 inside 函数,并且该函数具有调用 outside 绑定(bind)的数据到它。它“关闭”该数据。这些称为“闭包”。不要让这个名字打扰你,closures are not complicated .

And how does the second call to outside (outside(3)(5)) returned value (8) instead of the inner function (inside) unlike the first call?

outside的第二次调用确实返回一个函数(该调用生成的inside函数);但随后您将立即使用第二对 () 调用该函数。

线路

outside(3)(5);

...分解如下:

var f = outside(3); // Create and get the `inside` function bound to 3
f(5);               // Call it, passing in `5`

来自您的评论:

So what you mean is, in the first call of outside(3), the 'returned' inside method definition becomes(is changed to?) return 3 + y;. is that right?

接近,但不完全是。 x 的值不会被烧入 inside 中; inside 具有对其创建所在的上下文的引用,并且该上下文使其能够访问 x 参数。这些并不完全相同,如果我们稍微更新一下示例(并放弃数学,这只会使事情变得模糊),我们就会看到:

function outside(name) {
    // 'inside' uses the 'name' argument from the call to 'outside' that created it
    function inside() {
        return name;
    }

    // 'changer' *changes* the 'name' argument's value
    function makeCaps() {
        name = name.toUpperCase();
    }

    // Return both of them
    return {
        inside: inside,
        makeCaps: makeCaps
    };
}

var funcs = outside("foo");
funcs.inside();      // "foo", because 'inside' uses the 'name' created
                     // by the call to 'outside', and that 'name' is
                     // currently "foo"
funcs.makeCaps();    // Changes that same 'name'
funcs.inside();      // "FOO", because that 'name' has been changed

了解 insidechanger 都在相同的上下文(即调用 的上下文)上关闭是很关键的在创建它们的外部

了解每次调用 outside 都会创建新的上下文和新函数也很关键:

var funcs1 = outside("foo");
var funcs2 = outside("separate");
funcs1.inside();     // "foo"
funcs2.inside();     // "separate"
funcs1.makeCaps();
funcs1.inside();     // "FOO"
funcs2.inside();     // "separate"

关于javascript - 外部函数 "store"如何获取内部函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22035679/

相关文章:

javascript - 如何在 mongodb-native findAndModify 中使用变量作为字段名?

javascript - 在javascript中使用正则表达式和replace()替换数组元素

javascript - 悬停时平滑按钮增长和按钮收缩动画

function - 如何在后台作业脚本 block 中使用文件中的函数

python函数修改调用范围内的变量

javascript - "Readonly"block(div) 通过 CSS 或 JS+CSS

javascript - 使用 gulp-angular-templatecache 将 HTML 合并到 template.js 中,出现 $injector Module Unavailable 错误

python - 使用 csv 列作为函数参数

c++ - 如何在另一个函数中使用一个函数?

mysql - VB.Net 不使用数据库数据填充数组