簡體   English   中英

打字稿對象文字“this”關鍵字

[英]Typescript object literal “this” keyword

在對象字面量的函數中使用this時的預期行為是什么?

例如,假設我有一個foo類型,它只有一個名為bar的函數,沒有其他屬性。 但是在fooObj.bar方法中,我可以訪問this.baz (其中baz不是foo類型的屬性)我看不到任何錯誤。 不應該打字稿錯誤,因為fooObj上沒有baz嗎?

type foo = {
    bar(): void;
}
var fooObj: foo = {
    bar: () => {
        // TS does not error out when I access this.baz
        console.log(this.baz);
    }
} 

設置"noImplicitThis": true編譯器選項是您現在啟用此功能的方式。 此拉取請求啟用在對象文字中鍵入this Aleksey L 最初在對該問題的評論中建議了這個編譯器選項,但當時它並沒有那樣工作。

您正在使用具有詞法this的箭頭函數。

但是,對象字面量中非箭頭函數屬性的簡寫甚至更短:

var fooObj: foo = {
    bar() {
        console.log(this.baz);
    }
}

這個答案在提問時是正確的。 這已經隨着新版本的打字稿和目標 javascript 版本而改變。

您要求打字稿推斷thisfooObj

打字稿結合this通過創建一個局部變量_this ,綁定到this -context脂肪在哪兒箭頭聲明。 在您的情況下, this是全局范圍,即any 這是它被編譯成的內容:

var _this = this;
var fooObj = {
    bar: function () {
        // TS does not error out when I access this.baz
        console.log(_this.baz);
    }
};

這是它在類中的樣子:

class Bar
{
    private var = 23;
    public makeSound = () => console.log(this.var) 
}

// Compiles into:

var Bar = (function () {
    function Bar() {
        var _this = this;
        this.var = 23;
        this.makeSound = function () { return console.log(_this.var); };
    }
    return Bar;
}());

暫無
暫無

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

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