这 几乎 与我到目前为止阅读的所有其他 this
范围界定问题相同,除了一个细微的差异,这使得提出这个问题具有相关性 (imo)。
现在我的问题最初是用 Knockout 和 Typescript 确定 this
的范围,所以给出以下内容:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray(someJsonData: any)
{
this.SomeObservableArray.push(new SomePojo(someJsonData));
}
}
所以上面代码中的 this
位会爆炸,因为 Typescript 让你认为 this
是类实例,但实际上它是其他的 this 因为ajax 回调或 View 元素,无论覆盖 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));
};
}
}
我只是在脑海中写下这个示例代码,所以对于任何拼写错误等,我深表歉意,但它强调了所面临的常见问题和常见的解决方案/解决方法。
现在!我遇到的问题是下一步,我有这样的代码:
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 未定义
。
我确信 1 种可能的解决方案是提取 foreach 并使其成为自己的方法,但是这感觉就像将玻璃胶带粘在 blutack 上,所以我想知道是否有更优雅的解决方案或我的一些不当行为可以更改为至少不必使其更不可读。
最佳答案
是的,它实际上非常简单。只需在任何 方法上使用 lambda 表达式,您希望将范围限定在更高函数的范围内。在您的情况下,您需要将示例重写为:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray = (someJsonData: any) => Void;
constructor()
{
this.PopulateObservableArray = (someJsonArrayData: any) => {
this.SomeObservableArray.removeAll();
someJsonArrayData.forEach((someJsonData) => {
this.SomeObservableArray.push(new SomePojo(someJsonData));
});
};
}
}
PS:最好不要在 for each 中操作可观察数组,因为该数组的订阅者将在每次更改时收到通知。只需将您的数据推送到一个临时数组,然后将此数组设置为您的可观察数组的值(只是我的 2cts。)
关于javascript - Typescript 中此子范围的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15925500/