[英]Mongoose method scope in TypeScript
我在Mongoose方法的回调函数中有关于对象范围的问题。 我的员工有“地址”。 当您调用此“方法”时,它将在地址模型中查找地址。
使用Javascript:
employeeSchema.methods.getAddresses = function (callback) {
addressModel.find({ _id: { $in: this.addresses } }, function (err, obj) {
callback(obj);
});
};
我想输入所有内容,并且函数中的“ this”范围有问题。 作用域在对象本身上,但是所有示例都显示“ this”。 它在TypeScript中不起作用,因为它认为它是主类。
打字稿:
employeeSchema.methods.getAddresses = (callback) => {
addressModel.find({ _id: { $in: this.addresses } }, (err, obj) => {
callback(obj);
});
};
验证存在相同的问题:
accountSchema.path('email').validate(function (email, callback) {
if (this.isNew || this.isModified('email')) {}
}
'this'是回调范围内的帐户,但是有没有办法将对象实际传递给回调?
既然你不想要捕获的词法范围this
,不要使用=>
只需使用function
。
还有一个特征请求申报的含义this
是一个特定类型: https://github.com/Microsoft/TypeScript/issues/229
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.