我是打字新手 当我使用 jQuery 时,
export class IDE{
init():any{
$("select").on("change",function(){
this.run();//cannot working because we in jQuery context.
})
}
run():any{
}
}
这个关键字被 jQuery 'this' 关键字覆盖了,谁能给我一些想法?
最佳答案
您可以通过 3 种方式解决上下文问题,给您:
1) Use fat arrow :
$("select").on("change",() => {
this.run();
})
2) Use
bind
:
$("select").on("change",function(){
this.run();
}.bind(this)); // <----- HERE
3) Pass the reference of
this
:
export class IDE{
init():any {
let self = this;
$("select").on("change",function(){
self.run();
})
}
run():any{
}
}
Reason For Not Working Before : every new function defined its own this value (based on how function was called, a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an "object method", etc.)
关于jQuery this 关键字与 typescript this 冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51924756/