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?

asked Oct 28, 2015 at 18:03
6
  • because factory returns an object which you returned from at the end return { set: set, get: get } Commented Oct 28, 2015 at 18:08
  • I know it returns that object. But my question is - how come the savedData variable is 'visible' from the user code? Commented Oct 28, 2015 at 18:09
  • 2
    Please read about Closures Commented Oct 28, 2015 at 18:10
  • @user107986 also read up on this stackoverflow.com/a/23683176/2435473 Commented Oct 28, 2015 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. Commented Oct 28, 2015 at 18:12

1 Answer 1

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

answered Oct 28, 2015 at 18:13
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.