[英]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 最初在對該問題的評論中建議了這個編譯器選項,但當時它並沒有那樣工作。
這個答案在提問時是正確的。 這已經隨着新版本的打字稿和目標 javascript 版本而改變。
您要求打字稿推斷this
是fooObj
。
打字稿結合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.