【问题标题】:Losing context of this in a callback在回调中丢失 this 的上下文
【发布时间】: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

我也尝试过使用$.proxyvar self = this 无济于事。

谢谢!

【问题讨论】:

  • 您是否尝试过在 Web Inspector(或控制台)中通过回调调试/输出 this
  • 我在VocabApp 中没有看到任何controlsHolder 声明
  • 丹尼尔,我刚刚更新了我的问题。

标签: javascript jquery scope underscore.js


【解决方案1】:

请注意,初始化回调正在将提到的变量更改为 this.$element.find('nav.controls') 并且构造函数也在更改此变量。

我会说构造函数或 init 回调在 initUI 之后运行,然后更改了 controlsHolder 的值。

【讨论】:

  • 但是 this.test 工作正常!然而,它也在这两个地方设置。
猜你喜欢
  • 1970-01-01
  • 2017-02-18
  • 2018-06-02
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多