Home > Software design >  How to access grand-child's variable in a closure
How to access grand-child's variable in a closure

Time:01-22

I want to retrieve the values of a and b from p in the code given below. I would also like to run the function z from p. How do I achieve this?

function x() {
    var a = 10;
    return function y() {
        var b = 20;
        return function z() {
            console.log(a, b);
        }
    }
}
const p = x();

I'm new to JS.

CodePudding user response:

function x() {
    var a = 10;
    return function y() {
        var b = 20;
        return function z() {
            console.log(a,b)
        }
    }
}
// get function z
const result = x()();
console.log(result)
// get a,b 
result()

Calling x returns function y, calling y returns function z i.e. x()();
By calling function z, you can get a,b (return or console) i.e. x()()();

  • Related