问题
In this example, how may I get the value of the i var inside the for loop, into guardarReserva() function?
guardarReserva() and generarGrilla() are both methods of the same myApp object.
var myApp = {
generarGrilla:function(){
for(var i=1; i<13; i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
},
回答1:
You would need to define i outside of both functions:
var myApp = {
i:0,
generarGrilla:function(){
for(this.i=1; this.i<13; this.i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
console.log(this.i);//i is now accessible
},
You can also use a global variable:
var i;
var myApp = {
generarGrilla:function(){
for(i=1; i<13; i++){
var impresionGrilla = $('#grilla').append("one");
};
},
guardarReserva:function(){
var reservaConfirmada = $('#horario').append("two");
console.log(i);//i is now accessible
},
来源:https://stackoverflow.com/questions/35639060/js-how-may-i-access-a-variable-value-inside-a-function-thats-inside-another-fu