Javascript变量在一个函数中设置,但在另一个函数中未定义

标签 javascript jquery namespaces scope

我有以下 Javascript,

eventManager: {
    $musicGenres : null, // $musicGenres is the selector for a div-container of inputs
    musicGenres : [],

    // Functions
    handle : function(selectors) {
        selectors = (typeof selectors === 'undefined') ? {
            'musicGenres' : '#musicGenres'
        } : selectors; // selectors default values...
        this.$musicGenres = $(selectors['musicGenres']);
        console.log("CHANGED $musicGenres TO " + this.$musicGenres);

        this.$musicGenres.find('input').change(this.reloadMusicGenres);
    },
    reloadMusicGenres : function() {
        console.log("IN FUNCTION $musicGenres IS " + this.$musicGenres);
    },

,在我的页面上调用函数 eventManager.handle() 并触发其中一个输入的 change-Event,输出

CHANGED $musicGenres TO [object Object]
IN FUNCTION $musicGenres IS undefined

我不明白。我已将 $musicGenres 设置为新值,但在 reloadMusicGenres 函数中它仍未定义。即使我通过输入 eventManager.$musicGenres 通过控制台手动访问 $musicGenres 的值,它也会输出正确的值。

有人能帮帮我吗?这真让我担心。

最佳答案

thiscontext 已经改变。解决该问题的最简单方法是在函数外部引用 this,或传递一个 data 对象(正如另外两位出色的发帖人 Richard Healy 和 AlliterativeAlice 所建议的)。

第三种方法是显式绑定(bind) this 的上下文。使用 jQuery,您可以通过调用 $.proxy 来实现这一点。所以,这:

this.$musicGenres.find('input').change(this.reloadMusicGenres);

变成:

this.$musicGenres.find('input').change($.proxy(this.reloadMusicGenres, this));

$.proxy 将返回一个新函数,其中 this 将始终绑定(bind)到 eventManager。如果您有兴趣摆脱 jQuery,Function.prototype.bind 就是您的答案(编辑:Zoltan 的答案提供了一个示例)

以下是有关如何使用这些优秀功能的文档的一些链接:

jQuery 代理:https://api.jquery.com/jQuery.proxy/

绑定(bind)函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

关于Javascript变量在一个函数中设置,但在另一个函数中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30767791/

相关文章:

python - NameError 在 python 中使用 execfile

javascript - 如何根据下拉选择检查 tr 是否显示/隐藏

javascript - "document.createElement"如何作用于 "display"属性

javascript - 固定 div 右侧的悬停菜单

c++ - 将类放入 namespace

c# - 使用命名空间作为类型错误

javascript - 为什么日期对象的时间不改变?我怎样才能让它改变?

javascript - 使用 gifshot 从 base64 字符串数组创建 gif 在 Firefox 中不起作用

jQuery Mobile 输入字段错误样式

javascript - JQuery 添加淡入淡出效果