如何在TypeScript类的方法中从函数访问类成员

22

我有这段 TypeScript 代码:

    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成员字段?

3个回答

31

TypeScript 也支持箭头函数,保留了词法作用域。箭头函数的结果与 Jakub 的示例类似,但更加简洁,因为您无需自己创建变量和调整使用方式:

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

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

3
这是我对TypeScript最喜欢的事情之一。 - Maverick
如果在这个例子中也使用了“data”,那么这会更清晰明了。 - Serj Sagan
在原始问题中,data参数被命名为todos,因为这是调用提供的数据类型。如果您愿意,可以在上面的示例中使用data代替todostodos参数将包含jQuery传递给回调函数的数据对象。 - Fenton
@Sohnee,像上面展示的那样,'this' 对我不起作用。请参考问题链接并纠正我是否做错了什么。https://dev59.com/9Ofys4cB2Jgan1zniFcs - Microsoft Developer

13

你可以像在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..
        });
    }
}

2
啊哈..我缺乏JavaScript技能。 - Flores
3
虽然这样技术上是正确的,但使用箭头函数是更好的方法来完成这个任务。 - Boris Yankov
这种技巧适用于其他类似的情况。对我来说是一个正确的指引。 - JsAndDotNet

1

Fenton是正确的。

但你也可以这样做:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接