Doubt with revealing pattern

6

Is it possible to do this with revealing pattern?

the console always returns undefined

function FlashService() {

    return{
        get: get
    };

    var _abc = 'teste';

    function get() {
        console.log(_abc);
        return abc;
    }

}
    
asked by anonymous 28.10.2014 / 22:08

1 answer

8

You need to assign the value to the variable before returning. Because of the hoisting of variables and functions (which I explain in more detail in this other answer ), the variable declaration is raised to the top of the scope, but the assignment does not. In short, your code does not work because it's understood like this:

function FlashService() {
    function get() {
        console.log(_abc);
        return abc;
    }
    var _abc;

    return {
        get: get
    };

    _abc = 'teste';
}

Either, the return occurs before the value is assigned, and therefore the closure captures the variable with its initial value, undefined . The _abc = 'teste' part is not even executed.

It will work if you change to:

function FlashService() {
    var _abc = 'teste';

    return {
        get: get
    };

    function get() {
        console.log(_abc);
        return abc;
    }
}
    
28.10.2014 / 22:11