Skip to content Skip to sidebar Skip to footer

JS: How May I Access A Variable Value Inside A Function That's Inside Another Function, And That Both Functions Belong To The Same Object?

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 o

Solution 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
    },

Post a Comment for "JS: How May I Access A Variable Value Inside A Function That's Inside Another Function, And That Both Functions Belong To The Same Object?"