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;
}
}
Thank you comrade...
– Marcelo Aymone