【问题标题】:self = this but cannot access self.function within a callbackself = this 但无法在回调中访问 self.function
【发布时间】:2016-09-01 12:36:29
【问题描述】:

我有以下代码块来存储对this 的正确引用。 我在 Models.Image 使用 Mongoose。

class some {
    public one() {
        var self = this;
        this.another(); //edited: this.another() is not a function
        Models.Image.findById(id).then(function(data) {
            self.another(); //self.another is not a function
            ....
        });
    }
    public another() {
        ....
    }
}

linter 将 self 显示为 this 但是当我执行它时,给了我错误。这里发生了什么?如何解决?

该类是绑定到表达路由的路由处理程序。

我想补充更多。在one()(不是回调)中调用this.another() 仍然给我is not a function 错误。不知何故,this 没有引用该类。 可能是什么问题?

【问题讨论】:

  • 很难理解您包含的有限代码有什么问题。看起来应该没问题,但是由于存在问题,最好包含更多代码。附带说明一下,您甚至不需要这个 self = this,因为您可以使用箭头函数。
  • 你怎么打电话给one()
  • 我已经更新了问题。
  • 您是否尝试过使用箭头函数() => {} 代替?这样就不需要将this 分配给self
  • 您很有可能将some.one 指定为某种回调,它缺少上下文信息,正如@JohnnyHK 的评论所建议的那样。您需要将其更改为 () => some.one()some.one.bind(some)

标签: typescript this


【解决方案1】:

已编辑:该类是绑定到表达路由的路由处理程序。

问题可能就在这里。

由于方法one 的调用方式,this 未绑定到类some 的实例。问题不在于回调。在one 的第一行,this 已经有一个错误的值:

var self = this; // self has a wrong value because this has a wrong value 

【讨论】:

【解决方案2】:

another() 应该在 public one() 中:

class some {
    public one() {
        var self = this;
        Models.Image.findById(id).then(function(data) {
            self.another(); //self.another is not a function

            ....
        });
    }
    public another() {
        ....
    }
}

这样更好:

class some {
    public one() {
        var self = this;
        Models.Image.findById(id).then(function(data) {
            self.another(); //self.another is not a function
            ....
        });
        another() {
            ....
        }
    }
}

【讨论】:

  • 我不明白。你说的是什么问题,你是怎么解决的?
  • 这是你调用 self.another 的方式。 another() 需要公开 one()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-04
  • 2012-12-14
  • 2016-07-20
  • 2012-03-15
  • 2018-05-05
  • 1970-01-01
  • 2021-12-30
相关资源
最近更新 更多