3 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
鑒于您當(dāng)前的代碼,如果您希望能夠getCount多次調(diào)用它是不可能的- 您count在最高級(jí)別進(jìn)行了解構(gòu),一個(gè)原語(yǔ)。改變它的唯一方法是重新分配外部變量getCount,這是一個(gè)壞主意。
一個(gè)簡(jiǎn)單的解決方法是不將一個(gè)原語(yǔ)放在數(shù)組的第一個(gè)位置,而是使用一個(gè)返回內(nèi)部的函數(shù)_count:
function getCount() {
let _count = 1;
const _updateCount = () => {
_count = _count + 1;
};
return [() => _count, _updateCount];
}
const [getInternalCount, updateCount] = getCount();
console.log(getInternalCount()); /* <===== Expect initial count to be 1 */
updateCount();
console.log(getInternalCount()); /* <===== After calling updateCount I Expect count to be 2 */

TA貢獻(xiàn)1993條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用具有已實(shí)現(xiàn)toString方法的obect,并在原始期望環(huán)境中使用此變量來(lái)獲取計(jì)數(shù)。
function getCount() {
let _count = 1;
const _updateCount = () => {
_count = _count + 1;
};
return [{ toString: () => _count }, _updateCount];
}
const [count, updateCount] = getCount();
console.log(count + '');
updateCount();
console.log(count + '');

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
范圍_count不同于count您嘗試的范圍console.log
要顯示_count您必須使用函數(shù)訪問(wèn)它的值,如下所示:
function getCount() {
// This is visibile only to the function getCount
let _count = 1;
const _updateCount = () => {
_count = _count + 1;
};
const _showCount = () => {
console.log(_count);
}
return [_count, _updateCount, _showCount];
}
// Count here will be a different variable
const [count, updateCount, showCount] = getCount();
console.log(count); /* <===== Expect initial count to be 1 */
updateCount();
showCount(); // Will show ===> 2
updateCount();
showCount(); // Will show ===> 3
添加回答
舉報(bào)