This is ALMOST和其他人一样this
到目前为止,我已经读过范围界定问题,除了一个细微的差别之外,这使得提出这个问题变得有意义(imo)。
现在最初我的问题是范围this
使用 Knockout 和 Typescript,因此给出以下内容:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray(someJsonData: any)
{
this.SomeObservableArray.push(new SomePojo(someJsonData));
}
}
So the this
上面代码中的位会爆炸,因为 Typescript 让你认为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));
};
}
}
我只是凭空写下这个示例代码,所以我对任何拼写错误等表示歉意,但它强调了面临的常见问题和常见的解决方案/解决方法。
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
.
我确信一种可能的解决方案是提取 foreach 并使其成为自己的方法,但这感觉就像将cellotape粘在blutack上,所以我想知道是否有一些更优雅的解决方案或我的一些错误行为可以改变至少不必让它变得更加难以阅读。