3

I don't know how to ask correctly what I need, so let me try..

How can I pass a current variable content (literal) to a function dinamically created?

Maybe with this following code you understand better:

function MyClass(){

  for (i = 1; i <= 10; i++){
    this['show' + i] = function(){
      alert('You called show' + i);
    };
  }
}

var obj = new MyClass();

obj.show3();

What I would like to be displayed in alert is "You called show3" instead of "show11".

Thanks

Oswaldo
  • 3,296
  • 4
  • 25
  • 35
  • 3
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – James Thorpe Nov 19 '15 at 13:12
  • Thank you for all the replies. @Franceso, I liked your answer, however kaigorodov's is simpler, so I marked it as answer ok? – Oswaldo Nov 19 '15 at 13:42

2 Answers2

2

Since javascript doesn't have a block scope (until let in ECMAScript 6) your original function will be bound with the same value of i. Calling another that generate itself a new function you avoid that and you give to i different values.

function MyClass() {

  for (i = 1; i <= 10; i++) {
    this['show' + i] = myFunc(i);
  }
}

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

var obj = new MyClass();

obj.show3();
Francesco
  • 1,383
  • 7
  • 16
1

There is a mechanism called binding in JavaScript. You can bind scope and any variables to the function in order to use them inside function. Scope will define this keyword inside function. All other binded variables will be available as arguments thus i variable in this example will have not a global but local scope and have a value passed in function creation.

for (i = 1; i <= 10; i++){
    this['show' + i] = function(i){
      alert('You called show' + i);
    }.bind(this,i);
}
kaigorodov
  • 877
  • 9
  • 15