Jump to content

newbie - trying to use closures inside "for" loop


tytbone

Recommended Posts

I'm having some difficulty understanding how I can use closures, such as here: http://jsfiddle.net/gogfan/Yv5zP/1/

 

I'm trying to get the text to print out each person's first + last name, each on its own line. Problem is I assume a common one: I only get the last array item to actually appear as output.

 

I tried creating a closure like mentioned here, but I can't seem to get it to work correctly. Help would be appreciated, naturally.

<body><p id="demo"></p><script>var txt = "";function person(first, last) {    this.firstName = first;    this.lastName = last;}var myFather = new person("John", "Doe");var myMother = new person("Sally", "Rally");myPeople = [myFather, myMother];for (var i = 0; i < myPeople.length; i++) {    (function(i) {        txt = myPeople[i].firstName + " " + myPeople[i].lastName +          "<br/>";        document.getElementById("demo").innerHTML = txt;    })(i);}</script></body>
Link to comment
Share on other sites

First off you're overwriting txt in each iteration of the loop, not appending. So it'll only store info of the last element in the array

 

Secondly, you don't need to wrap that inside an anonymous function like that inside the for loop.

 

and lastly, thats technically not a closure. all that information is still be available in the global scope. if you can simply write " myPeople[0].firstName" anywhere and be able to both simply access and change the data, then its not in another scope and thus not a closure.

 

This would be closer to a closure:

var myPeople = [      person("John", "Doe"),      person("Sally", "Rally")    ],txt="";function person(first, last){  var firstName = first;  var lastName = last;    return {    first: function(){return firstName;},    last: function(){return lastName;}  };};for (var i=0; i<myPeople.length; i++){  txt += myPeople[i].first() +" "+myPeople[i].last();}document.getElementById("demo").innerHTML = txt;

in this example, "firstName" and "lastName" only exist inside the person function, if you try to directly access them outside the function, Javascript won't know what they are from the global scope. They are inside a different scope, the function "person" scope. And to bridge the two scopes together we make the person function return an object, which gives us a 'window' to be able to see these two variables. This way we can see and access the firstName and lastName, indirectly, but we cannot change the values. This enables us to have a certain amount of control/security over the data we make in javascript, its a way to let us utilize encapsulation.

Edited by Hadien
  • Like 1
Link to comment
Share on other sites

It might also be helpful if you explained what you were "hoping" to accomplish -- for example explain what you thought your approach accomplished or why you thought it was necessary or desirable.

  • Like 1
Link to comment
Share on other sites

First off you're overwriting txt in each iteration of the loop, not appending. So it'll only store info of the last element in the array

 

Secondly, you don't need to wrap that inside an anonymous function like that inside the for loop.

 

and lastly, thats technically not a closure. all that information is still be available in the global scope. if you can simply write " myPeople[0].firstName" anywhere and be able to both simply access and change the data, then its not in another scope and thus not a closure.

 

This would be closer to a closure:

...

in this example, "firstName" and "lastName" only exist inside the person function, if you try to directly access them outside the function, Javascript won't know what they are from the global scope. They are inside a different scope, the function "person" scope. And to bridge the two scopes together we make the person function return an object, which gives us a 'window' to be able to see these two variables. This way we can see and access the firstName and lastName, indirectly, but we cannot change the values. This enables us to have a certain amount of control/security over the data we make in javascript, its a way to let us utilize encapsulation.

 

Thanks, I think I understand it a little more, at least. Despite dabbling in programming the past few years I still have difficulties understanding, and unfortunately won't realize things that are obvious to the pros.

 

I was able to solve my problem simply by adding a "+" to the "txt = myPeople...", for 'txt += myPeople.firstName + " " + myPeople.lastName + "<br/>";'

 

 

It might also be helpful if you explained what you were "hoping" to accomplish -- for example explain what you thought your approach accomplished or why you thought it was necessary or desirable.

 

Thanks, I just now solved my problem, actually. What I was hoping to accomplish I did write above: "I'm trying to get the text to print out each person's first + last name, each on its own line. Problem is I assume a common one: I only get the last array item to actually appear as output." I thought a closure was necessary because that was the answer to a similar problem here.

 

But in any case, my problem is solved. I appreciate the help, though.

Edited by tytbone
Link to comment
Share on other sites

You said you were having trouble trying to use closures but you did not explain why you wanted closures.

 

Apologies for never writing back. I thought a closure was necessary because that was the answer to a similar problem that was solved here; I assumed I needed one for the issue I was having.

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...