簡體   English   中英

Typescript 設置 Class 本身在方法中的值,Inheritance 從基礎 Class

[英]Typescript Set Value of Class itself in Method, Inheritance from Base Class

如何以自己的方法設置 class 本身的值? 試圖利用this 收到以下錯誤。

export class ProductForm extends FormGroup {

    constructor(){
      super({
        productName: new FormControl()
      })
    }
   
    addMoreFieldsTest(): void {
      this = {
        productName: new FormControl(),
        productDescription: new FormControl()
     }
}

錯誤:賦值表達式的左側必須是變量或屬性訪問。

我可以使用 AddControl 方法,但是想設置 class 本身用於學習目的。

更新的答案

FormControl 的控件不直接駐留在 FormGroup class 上,而是駐留在 class 上的屬性內命名controls

因此,如果您只想添加到擴展 class 上的控件,您只需操作控件屬性。

    export class ExtendedFormGroup extends FormGroup {
      constructor(
        controls: { [k: string]: AbstractControl },
        validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions,
        asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[]
      ) {
        super({...controls, alwaysPresent: new FormControl()}, 
               validatorOrOpts, 
               asyncValidator
        );
        this.extendedProperties();
      }
    
      extendedProperties() {
        this.controls["additional_control"] = new FormControl("");
      }
    }

上面的示例做了兩件事

  • 將構造函數參數傳遞給 super,並在控件上添加一個額外的始終存在的項目。
  • 如您的原始問題中所反映的那樣直接操作controls屬性。

現在只需調用new ExtendedFormGroup({})將創建一個帶有兩個預定義控制器alwaysPresentadditional_control的 FormGroup

舊回應

Since JavaScript, and therefore TypeScript by extension implement classes in a way that are essentially just labelled blocks with prototypes on them, you can use the square bracket notation to access properties on the this scope of your class.

    class Parent {
      foo: string;
      constructor(foo: string) {
        this.foo = foo;
      }
    }
    
    class Child extends Parent {
      constructor(foo: string) {
        super(foo);
        this.assignPropertiesDirectly();
      }
    
      assignPropertiesDirectly() {
        this["bar"] = "Creates 'bar' on Child";
        this["foo"] = "overwrites foo with this text";
      }
    }

但是,這種方法很脆弱,因為它不僅完全違背了首先使用 TypeScript 的目的,而且還依賴於為屬性名稱鍵入字符串值,這充其量是維護起來很麻煩,最壞的情況是會出錯易於。

在我看來,您的問題可能是作文設計的一個很好的候選者。

暫無
暫無

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

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