0

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?

user107986
  • 1,461
  • 1
  • 17
  • 24
  • because factory returns an object which you returned from at the end `return { set: set, get: get }` – Pankaj Parkar Oct 28 '15 at 18:08
  • I know it returns that object. But my question is - how come the savedData variable is 'visible' from the user code? – user107986 Oct 28 '15 at 18:09
  • 2
    Please read about [Closures](https://en.wikipedia.org/wiki/Closure_%28computer_programming%29) – Alex Shesterov Oct 28 '15 at 18:10
  • @user107986 also read up on this http://stackoverflow.com/a/23683176/2435473 – Pankaj Parkar Oct 28 '15 at 18:10
  • That is how Javascript works. It guarantees that local variables remain accesible. They only get deallocated when the garbage collector detects that no reference to it is possible. – trincot Oct 28 '15 at 18:12
  • You may also refer one of the most popular question on SO http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – Kulbhushan Singh Oct 28 '15 at 18:19

1 Answers1

0

You need to dive deeper into JavaScript to understand it. But i can briefly explain you:

  1. savedData is defined at the same level as functions so they can use it inside from the closure.

  2. functions are passed as a reference, so the pointer to function is copied and points to this function, even from another field.

  3. The same with return statement: it can use get and set functions because they are in it's visibility scope.

Read more here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Closures

value type reference type object in javascript

Community
  • 1
  • 1
Romko
  • 1,808
  • 21
  • 27