Jump to content

Closures


Jim12345

Recommended Posts

Hello,

 

I am looking over code plus the concept of closures. Below is the code:

 

Closures are a powerful tool but can be tricky to understand. Mastering them, however, will allow you to write some very elegant code.

Here’s an example:

var saver = function (value) {    return function () {        return value;    };};var retriever = saver(10);alert(retriever());

So the code alerts 10. If you rewrite the last line to be console.log(retriever);

 

You get this:

 

function () { return value; }

 

I can watch the original code execute in Chrome Debugging Tools, but it doesn't help to understand it.

 

Does anyone know I resource where I can watch say a table where the functions get created and variables get passed? Or can you create the table right here?

 

Years ago a read a book about C and the author used tables to simulate memory locations for say functions, pointer to functions, variables and

passing values by reference, etc.

 

Thanks,

Jim

 

 

Link to comment
Share on other sites

Dave,

 

That is good to know but I was thinking it doesn't help me on this issue.

 

Old school code would look like this:

var saver = function (value) {return value;    };alert (saver(10));

I am still getting my 10 but without the extra function in a function.

 

Maybe a better example of a closure might help me here?

 

One that it is clear that, "now I know why closures are important" ?

 

Jim

Link to comment
Share on other sites

As I said, closures give you a way to have local static variables in functions. The example you have posted above seems pointless because it is pointless -- until you add a local variable.

var saver = (function() {    var value = 0;    return function() {        value++;        return value;    };}());

You will notice this looks a little different with the enclosing parenthesis -- but this merely forces the function to be executed immediately one time so that the returned function will be assigned to the saver var rather than the outer function.

 

(Note: a local static variable is a local variable that maintains its value after the function has finished running. Global variables are static until the page is reloaded, but ordinary local variables inside functions lose their values after the function ends.)

 

Closures are rather mysterious. They seem to occur whenever you define a function inside another function. Their primary purpose is to create isolated persistent (static) local variables.

Link to comment
Share on other sites

A closure is a context for executing a function where the function still has local variables available regardless of the scope in which it was executed. That can be a fairly confusing definition, but that's what a closure actually is.One common use for a closure is when you are looping over things to apply event handlers or things like that. Something like this:

for (var i = 0; i < 10; i++) {  document.getElementById('button' + i).onclick = function() {    document.getElementById('button' + i).value = 'Clicked';  }}
If you glance at that code, you might think that it is going to set a click handler on 10 buttons (button0, button1, button2, etc), where once you click on the button it will change the text of the button to "Clicked". That's not what it does though, because by the time you click on a button that loop will have already finished and i is going to be set to 10, so the button that it is trying to change the text for does not exist (button10). Moreover, all buttons will try to change the text of the same element instead of themselves. You can use a closure there to save the value of i for each button.
for (var i = 0; i < 10; i++) {  (function (nr) {    document.getElementById('button' + nr).onclick = function() {      document.getElementById('button' + nr).value = 'Clicked';    }  })(i);}
So now you have an anonymous function inside the loop which gets executed immediately, and you pass the value of i to that function. Inside that function, there is a local variable called nr. Since those functions are going to run in the same scope, nr will always be defined to whatever i was when that anonymous function was executed, so it's going to set the click handlers and work as expected.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...