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?

查看:36
本文介绍了JS:如何访问另一个函数内的函数内的变量值,并且两个函数都属于同一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,如何将 for 循环内的 i var 的值放入guardarReserva() 函数中?

guardarReserva() 和 genericarGrilla() 是同一个 myApp 对象的两种方法.

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");
    },

推荐答案

您需要在两个函数之外定义 i:

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

这篇关于JS:如何访问另一个函数内的函数内的变量值,并且两个函数都属于同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆