3

I'm not sure exactly how to describe what I want. I want to define a function with the parameters being a local VALUE not a reference.

say I have list of objects I want to create

for(i = 0; i < 10; i++){
  var div = document.createElement("div");
  div.onclick = function(){alert(i);};
  document.appendChild(div);
}

Now I believe in this example no matter what div I click on, it would alert "10"; as that is the last value of the variable i;

Is there a way/how do I create a function with the parameters being the value they are at the time I specify the function... if that makes any sense.

5

2 Answers 2

5

You need to create the function inside another function.

For example:

div.onclick = (function(innerI) {
    return function() { alert(innerI); }
})(i);

This code creates a function that takes a parameter and returns a function that uses the parameter. Since the parameter to the outer function is passed by value, it solves your problem.

It is usually clearer to make the outer function a separate, named function, like this:

function buildClickHandler(i) {
    return function() { alert(i); };
}

for(i = 0; i < 10; i++){
    var div = document.createElement("div");
    div.onclick = buildClickHandler(i);
    document.appendChild(div);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Now I suppose I have to curry the functions if I want to pass 'this' also? div.onclick= function(){somefunction(i,this)};
@Sheldon: Correct. Alternatively, someFunc.call(this, i) will allow you to use this inside of someFunc.
0

You could use an anonymous function:

for(i = 0; i < 10; i++){
    (function(i){
        var div = document.createElement("div");
        div.onclick = function(){alert(i);};
        document.appendChild(div);
    })(i)
}

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.