01/10/2018, 13:30
Con trỏ this trong typescript
Mọi người giải thích giúp mình tại sao this.user
lại bị báo undefined với ạ
File user.model.ts:
var Schema = mongoose.Schema;
let User = new Schema({
name: String
});
User.pre('save', function (next) {
this.name = this.name.trim();
next();
});
export default mongoose.model('Users', User);
File home.controller.ts:
class HomeRoute extends db {
user: any;
constructor() {
super();
this.user = new User();
}
public getAll(req: Request, res: Response, next: NextFunction) {
console.log(this.user); // in ra màn hình undefined
}
Bài liên quan
Ý bạn là sao vậy? -_-
Hàm của bạn là một middleware nên được gọi từ trong một hàm khác. this trỏ tới hàn đó nên undefined là đúng r. Bạn bind đối tượng HomeRoute xem.
Cảm ơn bạn, mình đã giải quyết được vấn đề