这与我到目前为止所读到的每个其他范围问题几乎相同,this除了一个微小的差异,这使得它(imo)提出这个问题是相关的.
现在我的问题是this使用Knockout和Typescript 确定范围,因此给出以下内容:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray(someJsonData: any)
{
this.SomeObservableArray.push(new SomePojo(someJsonData));
}
}
Run Code Online (Sandbox Code Playgroud)
所以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));
};
}
}
Run Code Online (Sandbox Code Playgroud)
我只是把这个示例代码写在我的头顶上,所以我为任何拼写错误等道歉,但它是所面临的常见问题和常见解决方案/解决方法.
现在!我的问题是从这里开始的下一步,我有这样的代码:
class ViewModel
{
public SomeObservableArray = new ko.observableArray();
public AddToTheObservableArray = (someJsonData: any) => Void;
constructor …Run Code Online (Sandbox Code Playgroud)