【问题标题】:How to access class member from function in method class in typescript如何从打字稿中方法类中的函数访问类成员
【发布时间】:2012-11-06 00:38:03
【问题描述】:

我有这个打字稿代码:

    module MyPage {

    export class MyVm {

        ToDo : string;

        Load() {
            //can access todo here by using this:
            this.ToDo = "test";

            $.get("GetUrl", function (servertodos) {
                //but how do I get to Todo here??
                this.ToDo(servertodos); //WRONG ToDo..
            });
        }
    }
}

问题是,如何访问 $.get 回调中的 todo 成员字段?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    芬顿是对的。

    但你也可以这样做:

     mycallback(todos, self) { self.todo(todos)); }
     $.get('url', mycallback(todos, this));
    

    【讨论】:

      【解决方案2】:

      TypeScript 还支持保留词法范围的箭头函数。箭头函数产生的代码与 Jakub 的示例类似,但更简洁,因为您不需要自己创建变量和调整用法:

      这是使用箭头函数的示例:

      $.get("GetUrl", (todos) => {
          this.ToDo(todos);
      });
      

      【讨论】:

      • 这是我最喜欢 Typescript 的地方之一。
      • 如果在这个例子中也使用了data,这可能会更清楚
      • @SerjSagan 在原始问题中,data 参数被命名为todos,因为这是调用提供的数据类型。如果您愿意,可以在上面的示例中使用data 代替todostodos 参数将包含 jQuery 传递给回调的数据对象。
      • @Sohnee 'this' 对我不起作用,如上所示。如果我做错了什么,请参考问题链接并纠正我。 stackoverflow.com/questions/37362178/…
      【解决方案3】:

      和你在 javascript 中做的一样

      export class MyVm {
          ToDo : string;
      
          Load() {
              //can access todo here by using this:
              this.ToDo = "test";
              var me = this;
      
              $.get("GetUrl", function (todos) {
                  //but how do I get to Todo here??
                  me.ToDo(todos); //WRONG ToDo..
              });
          }
      }
      

      【讨论】:

      • 啊哈..我缺乏 javascript 技能
      • 虽然这在技术上是正确的,但使用箭头函数是更好的方法。
      • 此技术适用于其他类似情况。对我来说是一个指向正确方向的指针。
      猜你喜欢
      • 1970-01-01
      • 2018-09-21
      • 2015-05-28
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      相关资源
      最近更新 更多