首页 > 解决方案 > 如何从定义为第一类属性的类中访问类的属性?

问题描述

假设我有 2 个类,SimpleClass 和 MyChart:

class SimpleClass {
    top: number;
    bottom: number;
    chart: MyChart;

    constructor() {
        this.chart = new MyChart();
    }
}


class MyChart {
    name: string;
    public method() {

    }
}

MyChart 的 method() 是否可以访问字段topbottom

标签: typescript

解决方案


MyChart 类是否始终是 SimpleClass 的属性?

在这种情况下,您可以将 SimpleClass 作为构造函数参数传递给 MyChart。

这将使它们之间产生强烈的耦合,因此根据您的场景,Alexander 传递您需要的属性的想法可能是一个不错的选择。您还可以定义一个特殊类型以传递给仅包含您需要的属性的构造函数,然后创建此传递的实例作为构造函数参数。

干杯!


推荐阅读