需要帮助,我卡住了!我给
function counter(){}
和我读了一些资料,设法想出了这个
function counter(){
var currentValue = 0;
var increment = function(val){
currentValue += val;
console.log(currentValue);
}
它不起作用,我还不能100%理解闭包。想知道什么是需要在代码和它是如何工作的。谢谢你!
基本思想是创建一个内部函数来捕获局部变量,然后将函数返回给调用者,调用者将调用它:
function counter(){
var currentValue = 0;
return function(val){
currentValue += val;
return currentValue;
}
}
// create a counter and increment by one
let c = counter()
console.log(c(1))
console.log(c(1))
console.log(c(1))
// create a new counter and increment it by 2
let e = counter()
console.log(e(2))
console.log(e(2))
console.log(e(2))
看起来每次运行函数时,您都将currentValue
变量更新为0
。一个简单的解决方案是将currentValue
变量定义为一个全局变量,如下所示:
var currentValue = 0;
function counter(val) { //where val is a number and the number you want your counter to change by
currentValue += val;
console.log(currentValue);
}
}
可能需要这段代码
function counter(){
var currentValue = 0;
return function(val){
currentValue += val;
return currentValue;
}
}
var c = counter();
console.log(c(10));
console.log(c(20));