Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6319825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T15:52:11+00:00 2026-05-24T15:52:11+00:00

So, I’m still reading Apress Pro Javascript Techniques and i’m having troubles with closures.

  • 0

So, I’m still reading Apress Pro Javascript Techniques and i’m having troubles with closures.

As John Resig states:

Closures allow you to reference variables that exist within the parent function.
However it does not provide the value of the variable at the time it is created; It provides the last value of the variable withing the parent function. The most common issue under which you’ll see this occurr during a for loop. There is one variable being used as an interaor (e.g., i). Inside of the for loop, new functions are being created that utilize the closure to reference the iterator again. The rpoblem is tat the time the new closured functions are called, they will reference the last value of the iterator (i.e., the last position in an array), not the value taht you woul expect.

Then he presents, in listing 2-16 an example using anonymous functions to induce scope.

/**
 * Listing 2-16. Example of Using Anonymous Functions to induce the 
 * Scope Needed to Create Multiple Closure-Using Functions 
 */
// An element with an ID of main
var obj = document.getElementById("main");

// An array of items to bind to
var items = ["click", "keypress"];

for (var i = 0; i < items.length; i++) {
    // Use a self executed anonymous function to induce scope
    (function() {
        // Remembre the value within this scope
        var item = items[i];

        // Bind a function to the element
        obj["on" + item] = function() {
            // item refers to a parent variable that has been successfully
            // scoped within the context of this loop
            alert("thanks for your " + item);
        };
    })();               
}

This example works as expected, and the behavious of the main object is correct.

The in the following, it uses another time a self-executing function to induce scope, during an iteration.

The purpose of the function is to create an object, defining getters and setters for all its properties. In this case, the example does not work.

/**
 * Listing 2-25. Example of Dynamicaaly Generated Methods That Are Created 
 * When a New Object is instantiated
 */          
// Create a new user object that accepts an object of properties
function User(properties) {
    // Iterate thorugh the properties of the object, and make sure
    // that it's properly scoped (sas discussed previously)
    var that = this;

    for (var i in properties) { 
       (function() {
           console.log("property: " + i);
           // Create a nwe getter for the property
           that["get" + i] = function() {
               return properties[i];
            };

            // Create a new setter  for the property
           that["set" + i] = function(val) {
               properties[i] = val;
           };
       })();                    
    }
}

// Create a new user object instance and pass in an object of
// properties to seed it with
var user = new User({
    name: "Bob",
    age: 44
});

// Just note that the name property does not exists, as it's private within the  
// properties object
alert(user.name == null);

// However, we're able to access its value using the new getnaem()
// method that was dynamically generated
console.log("name: " + user.getname());  // name: 44 :(
alert(user.getname() == "Bob");

// Finally, we can see that it's possible to set and gt the age using
// the newly generated functions

user.setage(22);
alert(user.getage() == 22);

Instead, after passing the i parameter as argument to the self-executing function,it works.

for (var i in properties) { 
       (function(prop) {
           console.log("property: " + i);
           // Create a nwe getter for the property
           that["get" + prop] = function() {
               return properties[prop];
            };

            // Create a new setter  for the property
           that["set" + prop] = function(val) {
               properties[prop] = val;
           };
       })(i);                   
    }

My question is:

  • Why in the first case (for loop), it is not necessary to pass the i parameter, while
    in the second (for in) it is needed in order to work properly?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T15:52:12+00:00Added an answer on May 24, 2026 at 3:52 pm

    In the first example you are declaring a copy of the contents of the array element in a local variable:

    var item = items[i];
    

    As the inline comment says, here we’re remembering the value within the closure scope.

    In the 2nd example, instead of passing i as a parameter, you could also have done:

       (function() {
    
           var prop = i; // See here!
    
           console.log("property: " + i);
           // Create a nwe getter for the property
           that["get" + prop] = function() {
               return properties[prop];
            };
    
            // Create a new setter  for the property
           that["set" + prop] = function(val) {
               properties[prop] = val;
           };
       })(); 
    

    Which makes both examples more similar.

    Similarly, you could also alter the first example to pass i as a parameter, rather than declaring it verbosely in a variable.

    (function(item) {
        // Bind a function to the element
        obj["on" + items[item] = function() {
            // item refers to a parent variable that has been successfully
            // scoped within the context of this loop
            alert("thanks for your " + items[item]);
        };
    })(i);     
    

    It’s arbitrary as to whether you declare a local copy of the variable using a var statement, or pass it as a parameter into your self executing function.

    Edit:

    @Zecc bought up a good point in the comments, which I’d like to explain:

    (function (i) {
    
        // using `i` works as expected. 
    
    }(i));
    

    Where as:

    (function () {
    
        var i = i;
    
        // using `i` doesn't work... i = undefined.
    
    }());
    

    This is because the var variable = value statement is effectively:

    (function () {
    
        var i;
    
        i = i;
    
    }());    
    

    and the var keyword always assigns the variable(s) following it with the value undefined.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I used javascript for loading a picture on my website depending on which small
We're building an app, our first using Rails 3, and we're having to build
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
Is it possible to replace javascript w/ HTML if JavaScript is not enabled on
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.