JavaScript:变量未定义

标签 javascript undefined

当我在 javascript 中使用变量时,会出现错误

ReferenceError: getalletje is not defined

,取决于我声明的位置。

这是我声明变量的地方:

get_name: function(){
        var getalletje = 5;
        return getalletje;
    },

我尝试使用变量的地方:

        self.$('.geldinuit-button').click(function(){

                self.screen_selector.show_popup('geldinuit',{
                    message: _t('Popup titel'),
                    comment: _t('getalletje'),
                    confirm: function(){
                        window.alert(getalletje);
                    },
                });

        });

它给出了这样的错误。

但是:如果我将 var getalletje = 5; 放在 self.$('.geldinuit-button').click(function(){ 之上,它就可以工作.

我需要做一些额外的事情吗?

编辑 Shomz:这是完整的代码:

.............                
self.set_smart_status(status.newValue);
            });

            this.$el.click(function(){
                self.pos.connect_to_proxy();
            });
        },
    });

    module.PosWidget = module.PosBaseWidget.extend({
        template: 'PosWidget',
        init: function() { 
            this._super(arguments[0],{});
            this.pos = new module.PosModel(this.session,{pos_widget:this});
            this.pos_widget = this; //So that pos_widget's childs have pos_widget set automatically

.............................
............................

    get_name: function(){
        var getalletje = 5;
        return getalletje;
    },
...........................
...........................
                self.$('.geldinuit-button').click(function(){

                        self.screen_selector.show_popup('geldinuit',{
                            message: _t('Popup titel'),
                            comment: _t('getalletje'),
                            confirm: function(){
                                window.alert( this.get_name() );
                            },
                        });

                });
..........................

最佳答案

这是一个范围问题 - 您声明的变量仅在本地可用。要获取其值,您可以执行以下操作:

confirm: function(){
    window.alert( yourObject.get_name() );
},

其中 yourObject 是您为其定义 get_name 方法的对象。

关于JavaScript:变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32011343/

相关文章:

javascript - jQuery 选择器忽略了来自单独上下文的元素

javascript - 查明函数是匿名的还是在对象中定义的

javascript - 在像 quizup 这样的多人游戏中,socket.io 房间在配对中是否有任何作用

javascript - 如何在angularJS中过滤多个动态值

javascript - 如何用 "-"替换数组中所有未定义的值?

c - 出现错误[Pe020] : identifier "" is undefined in IAR with an typedef enum

javascript - 使用 Impress.js 创建动画元素符号列表

javascript - 循环创建变量,函数/数组循环

php - 使用 laravel 发送电子邮件,但不识别变量

c - 对 *.h 文件中声明的函数的 undefined reference