TypeScript中关于this的闭包问题

  • 问题
    开发中遇到这么一个问题,Typescript和jQuery 同时使用时,this出现闭包问题,先上代码:
class CoursePage {
       public init(){
            $("#rankType").on("change", function () {
            let type = parseInt($(this)).val());

            if (type == 1) {
                this.getRankQuestions();
            } else {
                this.getRankToStudentQuestions();
            }
        });
      }

     public getRankToStudentQuestions(){
     
     }
}

在运行时有个错误,这里的this会变成页面的DOM元素,导致无法执行函数getRankToStudentQuestions

  • 解决方案
    定义变量 __this = this, 使得this对象的指向改变,修改后的代码为:
public init() {
       var __this = this;

       $("#rankType").on("change", function () {
           let type = parseInt($("#rankType").val());

           if (type == 1) {
               __this.getRankQuestions();
           } else {
               __this.getRankToStudentQuestions();
           }
       });
}
  1. Typescript, jQuery and the ‘this’ context causing issues
  2. Typescript + Jquery Ajax + this](http://stackoverflow.com/questions/15662038/typescript-jquery-ajax-this)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • (a fork of Airbnb's Javascript Style Guide) Strikingly ES...
    飘零_zyw阅读 4,894评论 1 2
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,803评论 19 139
  • 注意若是出现 找不到 freq的错误,把freq勾选掉,然后自己换sweep var为RFfreq
    WICKII阅读 4,642评论 0 0
  • 人眨一次眼睛,蝴蝶扇动一次翅膀,海洋掀起风暴,这个世界因此改变。
    斯瑞岛戈阅读 2,286评论 0 0

友情链接更多精彩内容