需要幫助,我被卡住了!我被賦予
function counter(){}
我閱讀了一些材料并設法想出了這個
function counter(){
var currentValue = 0;
var increment = function(val){
currentValue = val;
console.log(currentValue);
}
它不起作用,我還沒有真正 100% 理解閉包。想知道代碼中需要什么以及它是如何作業的。謝謝!
uj5u.com熱心網友回復:
基本思想是創建一個內部函式來捕獲區域變數,然后將該函式回傳給呼叫者,呼叫者將呼叫它:
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))
uj5u.com熱心網友回復:
看起來每次運行該函式時,都會將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);
}
}
uj5u.com熱心網友回復:
也許需要這個代碼
function counter(){
var currentValue = 0;
return function(val){
currentValue = val;
return currentValue;
}
}
var c = counter();
console.log(c(10));
console.log(c(20));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/339466.html
標籤:javascript 关闭 柜台
