闭包和柯里化中的引用如何在 js 中工作?

How does a reference in closure and currying work in js?

下面的程序让我很困惑,console.log()是我加的。

function add(a) {
    console.log("1");
    var total = a;
    console.log("2");
    var _fn = function (b) {
        console.log("3");
        total += b;
        console.log("4");
        return _fn;
    };
    console.log("5");
    _fn.toString = _fn.valueOf = function () {
        console.log("6");
        return total;
    };
    console.log("7");
    console.log("_fn: " + _fn);
    return _fn;
}

当我运行添加(1)(2)时,控制台显示:

1
2
5
7
6
_fn: 1
3
4
6
ƒ 3

我的问题是:

1) var _fn = function (b) {...}中,"return _fn"语句中的_fn指的是什么?如果是指自己,那不就是这样无限递归吗

var _fn = function (b) {
    total += b;
    return function (b) {
        total += b;
        return function (b) {
            total += b;
            return _fn;
            .
            .
            .
        }
    }
}

2) 在控制台中,它显示“_fn: 1”,这意味着返回了 1,但显然返回了 _fn(函数)以便继续计算。所以实际返回的_​​fn和控制台显示的值有冲突。

in var _fn = function (b) {...}, what does _fn refer to in "return _fn" statement?

return 语句表示调用此函数时,函数的 return 值将是(对)函数对象本身的(引用)。注意它return是函数对象,没有调用它。只是对象,没有调用。至少现在还没有....

If it refers to itself, then isn't it in infinite recursion like this ...

不,因为 return 值,即函数,不会立即被调用。这有点像这样做:

function g() {return g}
g()

运行 不会进入无限循环。您调用函数 g,然后返回 g。你可以自己做 g()()()()()()(),但仍然 "stops." 递归是函数 调用 本身,而不是 returns 本身!

In console, it showed "_fn: 1" which means 1 was returned, but apparently, _fn (the function) was returned so that the calculation could keep going. So there is a conflict between the actual returned _fn and the value shown in console.

嗯,说 1 是 returned 可能是不正确的;相反,代码会强制所有 console.log(以及类似的)生成 total 的当前值。在您执行 console.log 时,total 具有第一个参数的值,即 1。打印出所有这些数字非常聪明,因此它应该有助于您的理解。检查打印出 7 后,您还没有进行后续调用,其中进行了加法运算。这就是你看到 1 的原因。