I've come across the following code. It works, but I'm not sure why.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
The function returns an object that consists of two functions, set() and get(). But it doesn't return the function itself, so why does it even work? Shouldn't the variable savedData go out of scope? Or should I think of savedData as of a variable allocated on heap with new keyword in Java? As long as my code has a reference to it somewhere, it doesn't cease to exist?
1 Answer 1
You need to dive deeper into JavaScript to understand it. But i can briefly explain you:
savedDatais defined at the same level as functions so they can use it inside from theclosure.functions are passed as a
reference, so the pointer to function is copied and points to this function, even from another field.The same with
returnstatement: it can usegetandsetfunctions because they are in it's visibility scope.
Read more here:
https://developer.mozilla.org/en/docs/Web/JavaScript/Closures
return { set: set, get: get }