簡體   English   中英

如何從typescript中的方法類中的函數訪問類成員

[英]How to access class member from function in method class in 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成員字段?

TypeScript還支持保留詞法作用域的箭頭函數。 箭頭函數導致類似於Jakub示例的代碼但是更整潔,因為您不需要創建變量並自己調整用法:

以下是使用箭頭函數的示例:

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

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

芬頓是對的。

但你也可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM