Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dinamically create Javascript function with current variable values

Tags:

javascript

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

like image 258
Oswaldo Avatar asked May 16 '26 20:05

Oswaldo


2 Answers

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();
like image 194
Francesco Avatar answered May 19 '26 11:05

Francesco


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);
}
like image 33
kaigorodov Avatar answered May 19 '26 11:05

kaigorodov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!