Javascript - 从外部访问函数闭包中的变量
我想知道是否有某种方法可以从嵌套函数的外部获取已被嵌套函数捕获的变量的值.用文字解释有点棘手,所以这就是我想要实现的目标:
I was wondering if there was some way to obtain the value of a variable that has been captured by a nested function, from outside of that said function. A little tricky to explain in words so here's what I'm trying to achieve:
function counter(){
let count = 0;
return function counterIncrementer(){
++count;
}
}
function someReceiever(counterIncrementer){
// From here, somehow access the value of count captured by
// counterIncrementer.
// -> Without modifying the counter/returned counterIncrementer function
// before runtime
}
someReceiever(counter())
谢谢!
这样做的唯一方法是将 count 声明为全局,或者创建另一个仅用于访问 count 的函数,嵌套在 counter 中;但考虑到您的代码结构,这似乎不是一个很好的答案.
The only way to do this would be to declare count as a global, or create another function just for accessing count, nested within counter; but given the structure of your code, it doesn't seem like that's a great answer.
function counter(){
let count = 0;
return [
function counterIncrementer(){
++count;
},
function counterGetter() {
return count;
}
];
}
function someReceiever(counterIncrementerPack){
let counterIncrementer = counterIncrementerPack[0];
let counterGetter = counterIncrementerPack[1];
console.log(counterIncrementer(), counterGetter(), counterGetter(), counterIncrementer(), counterGetter());
}
someReceiever(counter())
输出:undefined 1 1 undefined 2
注意:您可能还想让 counterIncrementer 返回 ++count,但这不是问题耸肩.
Note: you may also want to make counterIncrementer return ++count, but that wasn't the question shrug.