下面的程序让我很困惑,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;
}
当我运行 add(1)(2) 时,控制台显示:
1
2
5
7
6
_fn: 1
3
4
6
ƒ 3
我的问题是:
1) 在 var _fn = function (b) {...} 中,_fn 在“return _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 语句表示调用此函数时,函数的返回值将是(对)函数对象本身的(引用)。注意它返回函数对象,没有调用它。只是对象,没有调用。至少现在还没有....
If it refers to itself, then isn't it in infinite recursion like this ...
不是,因为返回值,函数,并没有立即被调用。这有点像这样做:
function g() {return g}
g()
不会进入无限循环的运行。您调用函数 g,然后返回 g。您可以自己执行 g()()()()()()()
,但这仍然“停止”。递归是指函数调用 自身,而不是返回 自身!
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 被返回可能是不正确的;相反,代码会强制所有 console.log
(以及类似的)生成 total
的当前值。在您执行 console.log
时,total
具有您的第一个参数的值,即 1。打印出所有这些数字非常聪明,所以它应该帮助你的理解。检查打印出 7 后,您还没有进行后续调用,其中进行了加法运算。这就是你看到 1 的原因。
关于javascript - 闭包和柯里化(Currying)中的引用如何在 js 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51567907/