当我使用jQuery时,我是打字稿的新手,
export class IDE{
init():any{
$("select").on("change",function(){
this.run();//cannot working because we in jQuery context.
})
}
run():any{
}
}
Run Code Online (Sandbox Code Playgroud)
这个关键字被jQuery'this'关键字覆盖,有人可以给我一些想法吗?
您可以通过3种方式解决上下文问题,在这里您可以:
1)使用粗箭头:
$("select").on("change",() => {
this.run();
})
Run Code Online (Sandbox Code Playgroud)
2)使用
bind:
$("select").on("change",function(){
this.run();
}.bind(this)); // <----- HERE
Run Code Online (Sandbox Code Playgroud)
3)通过以下参考
this:
export class IDE{
init():any {
let self = this;
$("select").on("change",function(){
self.run();
})
}
run():any{
}
}
Run Code Online (Sandbox Code Playgroud)
之前无法工作的原因:每个新函数都定义了自己的该值(根据函数的调用方式,在构造函数中为新对象,在严格模式函数调用中未定义,如果该函数被称为“对象方法”等)
| 归档时间: |
|
| 查看次数: |
222 次 |
| 最近记录: |