【发布时间】:2015-08-17 22:23:37
【问题描述】:
这是我的代码的摘录:
'use strict'
var VocabApp = function (element, options) {
this.options =
this.$element = null
...
this.controlsHolder =
this.test =
this.init(element, options)
}
VocabApp.prototype.init = function (element, options) {
this.$element = $(element)
this.options = this.getOptions(options)
this.controlsHolder = this.$element.find('nav.controls')
this.test = 'foo'
...
}
VocabApp.prototype.initUI = function () {
console.log(this.controlsHolder)
console.log(this.test)
this.$element.find('.levels').on('click', ".level", _.bind(function (e) {
console.log(this.controlsHolder)
console.log(this.test)
}, this))
}
为什么console.log先打印出正确的元素,然后在回调内部打印出undefined? _.bind 不应该保留 this 的上下文吗?
奇怪的是this.test 在这两种情况下都能正确打印foo!
我也尝试过使用$.proxy 和var self = this 无济于事。
谢谢!
【问题讨论】:
-
您是否尝试过在 Web Inspector(或控制台)中通过回调调试/输出
this? -
我在
VocabApp中没有看到任何controlsHolder声明 -
丹尼尔,我刚刚更新了我的问题。
标签: javascript jquery scope underscore.js