gpt4 book ai didi

jQuery this 关键字与 typescript this 冲突

转载 作者:搜寻专家 更新时间:2023-10-30 22:06:13 25 4
gpt4 key购买 nike

我是打字新手当我使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com