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
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();
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With