簡體   English   中英

從TypeScript訪問JavaScript“this”

[英]Access JavaScript “this” from TypeScript

我目前正在使用我的打字稿項目中的AlpacaJS庫。 這個JavaScript / JQuery庫包含在我的Typescript類中,並希望我在json樣式對象中傳遞一些選項,如下所示:

this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(this.getValue());
                }
            }
        }
    }
};

通過這個對象,我說:將更改事件添加到羊駝生成的表單中的字段“id”。 在該函數中使用“this”給出了庫的“this”,而不是typescript類“this”。

問題 :如果我想在我的Typescript類中調用方法或變量怎么辦? 我將不得不使用“這個”,但“這個”綁定到羊駝/ javascript這個。 我無法將其更改為(event) => { ... }{ ...}.bind(this)因為這樣我可以訪問打字稿“this”,但我無法訪問羊駝/ javascript這個,我需要他們兩個....

我不能訪問羊駝/ javascript這個,我需要他們兩個

在創建函數之前使用捕獲this標准的javascript技巧:

let _self = this;
this.options = {
    "collapsible": false,
    "fields": {
        "id": {
            "events": {
                "change": function () {
                    console.log(_self.getValue());  // the class instance
                    console.log(this); // the lib version 
                }
            }
        }
    }
};

此提示也在此處記錄: https//basarat.gitbooks.io/typescript/content/docs/arrow-functions.html

暫無
暫無

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

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