Doubt with Revealing Pattern

Asked

Viewed 34 times

6

It is 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;
    }

}

1 answer

8


You need to assign the value to the variable before returning. Due to 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 is understood like this:

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

    return {
        get: get
    };

    _abc = 'teste';
}

If so, the return occurs before the value is assigned, and therefore the closure captures the variable with its initial value, undefined. The part of _abc = 'teste' nor is it executed.

It will work if you change to:

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

    return {
        get: get
    };

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.