簡體   English   中英

子類中父類的調用方法

[英]Call method from parent class inside child class

我最近開始學習javascript Classes ,在閱讀一些非常有趣的內容時,我想到了嘗試自己的一些想法。

如果您有Parent的父類,其中有一個logSomething```` and a child class of methodlogSomething```` and a child class of Child logSomething```` and a child class of Child擴展Parent logSomething```` and a child class of , with which you do , how can you then execute the inherited method from the parent class, logSomething ```,在孩子班里面嗎?

如果您在Child類中定義一個方法並將this.logSomething()添加到該方法中,則無論何時調用該子類中的方法,繼承的logSomething函數的確會運行,但除此之外,我還沒有找到任何方法直接在該子類內部執行logSomething

我嘗試過this.logSomething() ,我嘗試將其添加到對象,自執行(IIFE)函數以及我能做的所有事情,但沒有任何結果。

class Parent {
  constructor() {}

  logSomething() {
    console.log('I am logging something')
  }

}

class Child extends Paren {
  logSomething() // This does not work
}

當前這樣做是行不通的,如果拋出一個錯誤的事實,那就是您試圖定義一個函數的事實。

我知道應該以某種方式實現這一點,如果我不認為React使用與life-cycle methods類似的東西對嗎? componentWillMount

人們將如何去做呢?

第一個錯誤是您要擴展Paren而不是Parent
同樣,您不能只在類內部拋出隨機語句。 它必須在函數內部。
如果希望它在每次創建該類的實例時運行,則它應該在constructor或由其調用的函數中。 (請注意,您需要在構造函數的開頭調用super()
最后,您仍然需要使用this.logSomethingthis.logSomething

 class Parent { constructor() {} logSomething() { console.log('I am logging something'); } } class Child extends Parent { constructor() { super(); this.logSomething(); // Will use Parent#logSomething since Child doesn't contain logSomething super.logSomething(); // Will use Parent#logSomething } } new Child(); 

 class Parent { constructor() {} logSomething() { console.log('Parent Logging Called'); } } class Child extends Parent { constructor() { super(); this.logSomething(); // Will call Child#logSomething super.logSomething(); // Will call Parent#logSomething } logSomething() { console.log('Child Logging Called'); } } new Child(); 

您也可以這樣做:

 class Parent { constructor() {} logSomething() { console.log('Parent Logging Called'); } } class Child extends Parent { logSomething() { console.log('Child Logging Called and ...'); // Careful not use this.logSomething, unless if you are planning on making a recursive function super.logSomething(); } } new Child().logSomething(); 

您可以使用this調用任何函數或使用父類的任何屬性,只要新類對該屬性沒有自己的定義。

在這里查看更多信息。

class Parent {
  constructor() {}

  logSomething() {
    console.log('I am logging something')
  }

}

class Child extends Parent {
  logSomething() {
    super.logSomething(); // Call parent function
  }

}

a)您不能在那里調用函數,可以在類中聲明的函數中調用函數

b)您需要使用this.logSomething()

例:

 class Parent { constructor() {} logSomething() { console.log('I am logging something') } } class Child extends Parent { fn() { this.logSomething() // This does work } } new Child().fn() 

有關在子類中何時將fn稱為logSomething ,請參見其他答案-那么您需要用super.logSomething()來調用“父” logSomething而不是子logSomething

暫無
暫無

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

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