我的基地class:
import { Component, VERSION } from '@angular/core';
import { Feature } from './super.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent extends Feature {
name = 'Angular ' VERSION.major;
constructor() {
super();
}
superToCall(value) {
console.log('value', value);
}
}
超級class:
export class Feature {
childCalled(value) {
console.log('child called', value);
}
}
如何將引數傳遞給superToCallfromchildCalled方法?
現場演示
uj5u.com熱心網友回復:
經典的 OOP 模式:使用抽象方法將超類宣告為抽象類abstract superToCall(value: unknown):void。現在你可以從父類呼叫子類的方法this.superToCall(someValue)
export abstract class Feature {
childCalled(value: unknown) {
console.log('child called', value);
this.superToCall(value);
}
abstract superToCall(value: any): void;
}
export class AppComponent extends Feature {
superToCall(value: any) {
console.log('value', value);
}
}
uj5u.com熱心網友回復:
使您的父類 ( Feature) 抽象并添加一個抽象函式superToCall(子類必須實作):
export abstract class Feature {
childCalled(value) {
console.log('child called', value);
this.superToCall(value);
}
abstract superToCall(value);
}
所有孩子(擴展Feature)現在必須實作抽象方法superToCall:
export class AppComponent extends Feature {
constructor() {
super();
}
override superToCall(value) {
console.log('value', value);
}
}
Stackblitz 示例
uj5u.com熱心網友回復:
這對我有幫助:
ParentClass.prototype.myMethod.call(this)
使用引數呼叫:
import { AppComponent } from './app.component';
export class Feature {
childCalled(value) {
AppComponent.prototype.superToCall.call(this, value)
}
}
uj5u.com熱心網友回復:
如果它存在于孩子身上,你可以只測驗它,然后呼叫它:
export class Feature {
childCalled (value) {
if (this.superToCall)
this.superToCall(value)
else
console.error(`superToCall does not exist on ${ this }`)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532576.html
標籤:javascript有角度的打字稿ecmascript-6
下一篇:node_modules/@types/lodash/ts4.1/common/lang.d.ts(578,74)中的錯誤:錯誤TS2677:型別謂詞的型別必須可分配給其引數的型別
