【问题标题】:Undefined even with null check即使使用空检查也未定义
【发布时间】:2019-02-20 05:09:32
【问题描述】:

listener 返回 undefined,我相信 start 属性。这是一个观察者对象。

    var updateP = {
        cb: function (event, properties) {
            "listener" in window? listener.next(properties):null
        },
        start: function (listener) {
            dataset.on("update", this.cb)
        },
        stop: function () {
            dataset.off("update", this.cb)
        },
    }

【问题讨论】:

  • 由于描述模糊,很难帮助您解决上述问题。你能提供更多细节吗?像这样想:你试图解释一些你很清楚,但其他人不知道的事情。从这个角度出发。
  • listener 没有在 cb 内部定义,如果这就是你的意思。 JavaScript 使用lexical scopestart 中的变量 listener 不会在 cb 中神奇地可用。
  • 是的,可以回答。
  • 有没有办法让我不必重复自己写出来?

标签: javascript scope


【解决方案1】:

listener 变量是 start 函数的局部变量,因此您不能将其作为全局变量访问。

this.cb的定义移到updateP.start里面,就可以访问词法变量了。

var updateP = {
  start: function(listener) {
    function asdf(ab) {
      console.log(ab)
    }
    this.cb = function(event, properties) {
      listener.next(properties)
    };
    dataset.on("update", this.cb)
  },
  stop: function() {
    if (this.cb) {
      dataset.off("update", this.cb);
    }
  },
}

【讨论】:

    猜你喜欢
    • 2017-10-09
    • 2022-11-26
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 2020-06-06
    • 2012-09-03
    • 1970-01-01
    相关资源
    最近更新 更多