簡體   English   中英

Typescript - 將子屬性“鏈接”到父屬性中的相同屬性,因此當更新父屬性時,它會更新子屬性中的相同屬性嗎?

[英]Typescript - "Link" a child attribute to the same attribute in the parent, so when the parent attribute is updated, it updates the same in the child?

公司可以有 Pia 協議,但不一定要有。 所以,我有以下 .ts 類來演示這一點。

我只是這樣做let submitObject = new Company(); 然后我得到一個公司 object,默認值為 null,我可以根據我的表單中的內容覆蓋這些值。

在此處輸入圖像描述

當我在公司中設置“id”時,我希望它也使用相同的值設置子 (Pia) 的“companyId”。 有沒有辦法讓它自動執行此操作,或者我是否需要在每次完成新公司 object 的值設置后手動執行submitObject.pia.companyId = submitObject.id submitObject.id?

公司.ts

import { Pia } from "./Pia";

export class Company {
    id: number = null;
    name: string = null;
    address: string = null;
    authRequired: boolean = false;
    piaRequired: boolean = false;

    pia: Pia = new Pia;
}

皮亞茨

export class Pia {
    companyId: number = null;
    agreementNumber: string = null;
    effectiveDate: string = null;
    expirationDate: string = null;
}

我試過的:

使用extends / inheritance (我很確定我做錯了)

公司.ts

import { Pia } from "./Pia";

export class Company {
    constructor(public companyId: number) {
        this.id = companyId;
    }
    id: number = null;
    name: string = null;
    address: string = null;
    authRequired: boolean = false;
    piaRequired: boolean = false;
    pia: Pia = new Pia(this.companyId);
}

皮亞茨

import { Company } from "./Company";

export class Pia extends Company {

    // constructor(companyId: number) {
    //     super(companyId);
    // }

    // companyId: number = super.id;
    companyId: number = null;
    agreementNumber: string = null;
    effectiveDate: string = null;
    expirationDate: string = null;
}

您可以使用getter/setter ,盡管如果您有更多想要“鏈接”的屬性,這可能會失控:

 class Pia { companyId; constructor(id) { this.companyId = id } } class Company { pia; constructor(pia) { this.pia = pia } get id() { return this.pia.companyId } set id(id) { this.pia.companyId = id } } const c = new Company(new Pia(42)); // c.id += 27 // also works c.id = c.id + 27; // 'linked', inner object was also updated console.log(c.pia.companyId);

請注意,它並不是真正的“鏈接”,只是公司的id成員充當外部代碼和內部 Pia 對象的companyId之間的代理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM