這是幾乎相同的所有其他this
範圍問題我讀過目前爲止,除了一個微小的差異,這使得它相關(imo)問這個問題。問題與兒童範圍這在打字稿
現在本來我的問題與淘汰賽和打字稿範圍界定的this
,所以給出如下:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray(someJsonData: any)
{
this.SomeObservableArray.push(new SomePojo(someJsonData));
}
}
所以在上面的代碼中this
位將炸燬因爲打字稿讓你認爲this
是類例如,但實際上它是因爲Ajax回調或視圖元素的一些其他這一點,無論是覆蓋this
關鍵字的情況。
所以要解決這個問題,大多數解決方案都是將該代碼移動到類的構造函數中,我個人覺得這很恐怖,但是考慮到使用TypeScript獲得的其他好處,這種少量的恐怖是可以接受的。所以只是讓大家都在同一頁上,下面的代碼解決了上述問題:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray = (someJsonData: any) => Void;
constructor
{
this.AddToTheObservableArray = (someJsonData: any) => {
this.SomeObservableArray.push(new SomePojo(someJsonData));
};
}
}
我只是寫這個例子的代碼了我的頭頂部,所以我對任何錯別字等道歉,但它hilights的共同面臨的問題以及常見的解決方案/解決方法。
NOW!我有問題,就是從這裏開始的下一步計劃,我有一些代碼,像這樣:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray = (someJsonData: any) => Void;
constructor
{
this.PopulateObservableArray = (someJsonArrayData: any) => {
this.SomeObservableArray.removeAll();
someJsonArrayData.forEach(function(someJsonData) {
this.SomeObservableArray.push(new SomePojo(someJsonData));
});
};
}
}
所輸出的代碼看起來像這樣:
var ViewModel = (function(){
function ViewModel(){
var _this = this;
this.SomeObservableArray = new ko.observableArray();
this.AddMultipleEntitiesToObservableArray = function(someJsonArrayData) {
_this.SomeObservableArray.removeAll();
someJsonArrayData.forEach(function(someJsonData) {
this.SomeObservableArray.push(new SomePojo(someJsonData));
});
}
};
return ViewModel;
})();
我再次對任何錯字道歉,因爲我只是簡化較大的項目輸出,但是在這裏看到的主要的事情是,在foreach方法孩子this
仍然存在,所以我得到的錯誤this.SomeObservableArray is undefined
。
我確信1個可能的解決方案是提取出來的foreach並使其成爲自己的方法,然而,這感覺就像在blutack上粘貼細胞帶,所以我想知道是否有一些更優雅的解決方案或我的一些不當行爲這可以改變,至少不必讓它更難讀。
我在TypeScript https:// www上做了關於this這個主題的視頻教程。 youtube.com/watch?v=tvocUcbCupA&hd=1 – basarat 2014-04-21 05:41:32