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)

你可能感兴趣的:(TypeScript中关于this的闭包问题)