我在TypeScript中有以下类:
class Log
{
public id: number;
public text: string;
construct(text: string){
this.text = text;
}
save(){
db.run(
`insert into logs(text) values (?) `,
this.text,
((this: RunResult, err: Error | null) => {
if(err){
//...
}
console.log(this);//expecting RunResult{} but Log{}
})
)
}
}
字符串
我想在回调函数块中使用RunResult.lastID
来更新日志示例的id,@types/sqlite3/index.d.ts
包含以下声明:
run(params: any, callback?: (this: RunResult, err: Error | null) => void): this;
型
但是,回调参数中的this
是Log类型,而不是RunResult类型。
如何获取正确的RunResult示例?this.lastID
需要一个值,而不是undefined
1条答案
按热度按时间ny6fqffe1#
run
函数parameters中的this
关键字不是要传递的参数,但它是函数上下文。此外,arrow函数没有上下文,因此回调函数中的this
关键字引用Log
类是正确的。因此,首先,您必须在回调之外保留
Log
类上下文,并使用普通函数作为回调,而不是箭头函数。下面是修改后的
save
函数:字符串