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?

扶醉桌前 提交于 2019-12-11 11:49:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!