【问题标题】:TypeScript Array of objects with reference and push() method带有引用和 push() 方法的 TypeScript 对象数组
【发布时间】:2019-02-12 12:11:04
【问题描述】:

最近我在我的代码中发现了一个障碍。我正在使用我的自定义对象和它们的数组。我发现一种情况下 push() 方法有效,另一种情况无效。

第一种情况(工作正常):

class MyObject{
  private reference: d3.Selection<SVGElement>;

  public constructor(ref: d3.Selection<SVGElement>){
    this.reference = ref;
  }
}

interface ViewModel{
  objects: MyObject[] 
}

class MyApp{
  private root: d3.Selection<SVGElement>

  private viewModel: ViewModel;

  constructor(options: Type){
    this.root = options.root
    this.viewModel.objects.push(new MyObject(this.root))
  }
}

第二种情况(不工作):

class MyObject{
  private reference: d3.Selection<SVGElement>;

  public constructor(ref: d3.Selection<SVGElement>){
    this.reference = ref;
  }
}

class MyApp{
  private root: d3.Selection<SVGElement>

  private objects: MyObject[];

  constructor(options: Type){
    this.root = options.root
    this.objects.push(new MyObject(this.root)) //seems to freeze the whole program
  }
}

我做错了什么? 任何帮助将不胜感激。

迈克尔

【问题讨论】:

    标签: arrays typescript object interface


    【解决方案1】:

    你还没有初始化你的objects数组:

    private objects: MyObject[] = [];
    

    这可能行得通:)

    虽然,您尚未在“工作”示例中初始化 viewModel。所以我想你发布了你的代码的剥离版本?

    【讨论】:

    • 是的 :) 正是那个。非常感谢!
    猜你喜欢
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多