jQuery this 关键字与 typescript this 冲突

标签 jquery typescript

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

相关文章:

typescript - Twin.Macro(样式化组件)+ NextJS 中的 Typescript : Argument of type 'Interpolation<never>' is not assignable to parameter of type

Typescript - 如何将对象转换为界面

jquery - 图像 block 问题内的图像比例

javascript - 当用户标记复选框时触发 jquery 操作

javascript - jQuery store .each() .text() 可以 chop 吗?

reactjs - 如何使我的 React 上下文提供程序类型安全

javascript - typescript 文件和 javascript 文件中的文件名相同

javascript - 如何在 JSON.parse() 之后将 JSON 数据显示到 HTML DOM 元素?

javascript - 如何添加一个 EventListener 来监听除特定元素之外的窗口上的每次点击

reactjs - 带有 yup 验证的对象或字符串类型有条件