簡體   English   中英

類中擴展類的使用方法

[英]Using method of an extended class in a class

我正在嘗試在擴展類中使用擴展類的方法(這可能不是很清楚,但請看下面的示例,您將會理解)。

我的模塊是用打字稿制作的:

export default class Test1 {
  private storedCond: string;

  public cond = (cond: string) => {
    this.storedCond = cond;
    return this.storedCond.length;
  };
  public getStoredCond = () => this.storedCond;
}

然后我想使用的是js文件中的某些方式:

import Test1 from './modules/Test1';

class Test2 extends Test1 {
  // this line is not working, how can i make it work ?
  this.cond('a futur dynamic string');

  final = () => `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}

const test = new Test2();

console.log(test.final());

我的Test1模塊有點像商店,我可以做這樣的事情: sotredCond = this.cond('a futur dynamic string'); 在我的Test2類中,但這不是我想要做的。 我想在Test2類中提供一個字符串( cond )並將其存儲在Test1模塊中。

您可以在類Test2使用構造函數

import Test1 from './modules/Test1';

class Test2 extends Test1 {

  constructor(cond: string) {
    this.cond(cond);
  }

  public final = () => `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}

const test = new Test2('a futur dynamic string');

console.log(test.final());

每次調用new Test2(arg) ,都會執行構造函數。

在這里查看文檔

@Nathan Bruet的答案有效,但這不是我真正想要的。

但是@Keith的評論是正確的。

我的Test2類的最終代碼是:

class Test2 extends Test1 {
  constructor() {
    super();
    this.cond('a futur dynamic string');
  }

  final = () =>
    `${this.getStoredCond()} is ${this.getStoredCond().length} length`;
}

暫無
暫無

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

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