Eladian
Eladian

Reputation: 958

Javascript - Access variable in function closure from outside

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())

Thanks !

Upvotes: 1

Views: 2880

Answers (2)

Sam Clarke
Sam Clarke

Reputation: 120

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())

Outputs: undefined 1 1 undefined 2

Note: you may also want to make counterIncrementer return ++count, but that wasn't the question shrug.

Upvotes: 0

Szab
Szab

Reputation: 1263

By my best knowledge - it's not possible to do that. The count value is a part of the counter function and is accessible only in this scope or in the scope of functions created inside that function (so basically closures).

I think you might find this thread useful: Accessing variables trapped by closure

Upvotes: 1

Related Questions