简体   繁体   English

JS:如何访问另一个函数内部的函数中的变量值,并且两个函数都属于同一对象?

[英]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? 在此示例中,如何将for循环中的i var值获取到guardarReserva()函数中?

guardarReserva() and generarGrilla() are both methods of the same myApp object . guardarReserva()和GenerarGrilla()都是同一个myApp对象的方法

var myApp = {
    generarGrilla:function(){
        for(var i=1; i<13; i++){
            var impresionGrilla = $('#grilla').append("one");
        };
    },
    guardarReserva:function(){
        var reservaConfirmada = $('#horario').append("two");
    },

You would need to define i outside of both functions: 您需要在两个函数之外定义i

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM