Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access grand-child's variable in a closure

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading