Typescript 如何从定义为第一个类的属性的类中访问类的属性?
假设我有两个类,SimpleClass和MyChart:Typescript 如何从定义为第一个类的属性的类中访问类的属性?,typescript,Typescript,假设我有两个类,SimpleClass和MyChart: class SimpleClass { top: number; bottom: number; chart: MyChart; constructor() { this.chart = new MyChart(); } } class MyChart { name: string; public method() { } } MyChart的方法(
class SimpleClass {
top: number;
bottom: number;
chart: MyChart;
constructor() {
this.chart = new MyChart();
}
}
class MyChart {
name: string;
public method() {
}
}
MyChart的方法()是否可以访问字段
top
和bottom
?MyChart类是否始终是SimpleClass的属性
在这种情况下,可以将SimpleClass作为构造函数参数传递给MyChart
这将使它们之间产生强耦合,因此根据您的场景,Alexander传递所需属性的想法可能是一个不错的选择。您还可以定义一个特殊类型来传递到只包含所需属性的构造函数中,然后创建此传递的实例作为构造函数参数
干杯 不,您必须将top和bottom作为参数传递,或者在MyChartThank中保留对某个类的引用。如何将SImpleClass作为构造函数参数传递给MyChart:this.chart=new MyChart();-MyChart括号内是什么?您可以执行如下操作:this.chart=new MyChart(this)