【发布时间】: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