[英]Function does not return the value
function Increment()
{
var counter = 100;
function inner()
{
counter += counter;
return counter;
}
}
var x = Increment();
console.log(x);
console.log(x);
console.log(x);
这是此代码的说明 使用 JavaScript 闭包/自调用方法执行以下操作: a) 将外部 function 命名为“增量”。 b) 将 100 作为计数器存储在外部 function 中。 c) 在内部函数中将计数器增加 100 并返回。 d) 调用“Increment” 3 次,每次将返回值存储在一个变量中。 e) 在 web 控制台中记录最终值(400 是第三次调用的最终值),但 function 甚至不返回第一个值。
大家能看出问题出在哪里吗?
您应该调用“内部” function 来执行它。
并且您的增量 function 应该返回或更新计数器变量以使其生效。
您还应该在外部声明计数器变量,以便每次调用“增量”Function 时都可以递增它。
如果你在里面声明它,它只会在你每次调用“增量”function 时重置。
你可以这样做。
function Increment()
{
function inner()
{
counter += 100;
return counter;
}
return inner();
}
var counter = 100;
console.log(Increment());
console.log(Increment());
console.log(Increment());
您不仅要调用内部 function 还要返回其结果。 下面的代码有效
var counter = 100; function Increment() { function inner() { counter += counter; return counter; } return inner(); } var x = Increment(); var y = Increment(); console.log(x); console.log(y);
内层function需要调用3次,所以需要在外层function中返回内层function并调用。
function Increment() { var counter = 100; function inner() { counter += counter; return counter; } return inner; } var x = Increment(); console.log(x()); console.log(x()); console.log(x());
如果最终值需要为 400,您可以像这样重写您的 function:
function Increment() { var counter = 0; function inner() { counter += counter || 100; return counter; } return inner; } var x = Increment(); console.log(x()); console.log(x()); console.log(x());
Increment()
不返回任何内容或undefined
。
如果您希望 Increment 返回 counter 的值,只需添加一个return
语句。
function Increment() {
let counter = 100;
function inner() {
counter += counter;
return counter;
}
return counter;
}
let x = Increment();
console.log(x); // 100
console.log(x); // no change, since `Increment()`
console.log(x); // was only called once
记住, inner
永远不会被调用——如果你想让 inner 做某事,调用inner()
。 此外,请记住, counter
是在Increment()
中声明的,这意味着每次调用它时,都会重新声明它(并重置为 100)
这些指令不会产生他们预期的结果。
这可能是他们真正想要的。
function Increment() { var counter = 100; function inner() { counter += 100; return counter; } return inner; } var innerFunc = Increment(); var a = innerFunc(); var b = innerFunc(); var c = innerFunc(); console.log(c);
Increment
改变了两件事。
首先, inner
function 将计数器增加100
。 这是必需的,因为counter
发生了变化,因此counter += counter
导致counter
增加最近更新的版本。
其次, inner
function 成为Increment
的返回值。
因此,您只需调用一次Increment
,并将其结果存储在一个变量中。 该变量包含您返回的inner
function。 现在每次调用 function 时,它都会将counter
变量增加100
并返回其新值。
这是对闭包的正确演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.