Javascript - 从外部访问函数闭包中的变量 [英] Javascript - Access variable in function closure from outside

查看:48
本文介绍了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.

这篇关于Javascript - 从外部访问函数闭包中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆