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?