我有以下 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 的值,它也会输出正确的值。
有人能帮帮我吗?这真让我担心。
最佳答案
this
的context
已经改变。解决该问题的最简单方法是在函数外部引用 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/