1

I'm learning Javascript and I cannot understand why this code works:

function getObj()
{
   var objAddress = 
   {
      address: "Client Address",
      getAddress: function() {
         return this.address;
      },
      setAddress: function(newAddress)
      {
         this.address = newAddress;
      }
   };

   var objClient =
   {
      name: "Client name",
      getAddress: function()
      {
         return objAddress.getAddress();
      },
      setAddress: function(newAddress) {
         objAddress.setAddress(newAddress);
      }
   };

   return objClient;
}

gObj = getObj();
console.log(gObj.getAddress()); // Will print "Client Address"
gObj.setAddress("xpto");
console.log(gObj.getAddress()); // Will print "xpto"

I thought it would not work since getAddress() calls another method of an object that should not exist after leaving the function. But, as this is working, I presume that the object objAddress still exists even after quiting the getObj function.

Outside the function, how can the gObj.getAddress() work?

3
  • 2
    Read about closures, they are very important. Commented Nov 4, 2013 at 15:18
  • 1
    What makes you think the method getAddress() calls doesn't exist? Commented Nov 4, 2013 at 15:20
  • I came from C/C++ and, mistankenly,I think that, after the return statement, all the local variables of the function will be deleted. So, the objAddress will be deteled also. Commented Nov 4, 2013 at 15:29

3 Answers 3

3

When you create function, which uses local variable, function "remembers" this local variable. All needed local variables are stored in special object called closure. You cannot directly access it, but function can. Chrome Developer Tools in javascript debug shows closure object:Closure in Chrome Developer Tools

Sign up to request clarification or add additional context in comments.

Comments

1

This is called a closure. From the MDN page:

variables from the parent function of the closure remain bound from the parent's scope. (link)

That is to say, functions exist with a reference to the scope that they were defined in. As long as functions with a reference to the scope exist, the scope will exist.

Comments

0

getObj is a closure and in here:

gObj = getObj();

gObj is an instance of that closure and so all functions and properties that are defined in that class is valid for oObj too.

Comments

Your Answer

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.