我嘗試了以下方法來創建介面并實作它。
class AInterface {
constructor () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
通過擴展它在一個類中實作它。(請注意,我使用 ts-mixer 來實作多重繼承。
import AInterface from './AInterface'
import { Mixin } from 'ts-mixer'
class ClassA extends Mixin(AnotherClass, AInterface) {
constructor () {
super()
}
methodA () {
return 'test'
}
methodB () {
return 'test'
}
}
export default ClassA
這將引發錯誤class should implement a methodA() method。這意味著我在界面中所做的檢查失敗了 if (!this.methodA)。當我洗掉 Mixin 并僅擴展介面時,這很好用。( class ClassA extends AInterface)
有沒有更好的方法來做到這一點,或者我該如何解決這個問題?
節點版本 - 14
uj5u.com熱心網友回復:
問題似乎是 的建構式AInterface不正確this。所以它看不到methodAor methodB。
解決方法是避免在建構式中進行該檢查。
import AInterface from "./AInterface.mjs";
import { Mixin, settings } from "ts-mixer";
settings.initFunction = "init";
class ClassA extends Mixin(AnotherClass, AInterface) {}
介面.js
class AInterface {
init () {
if (!this.methodA) {
throw new Error('class should implement a methodA() method')
} else if (!this.methodB) {
throw new Error('class should implement a methodB() method')
}
}
}
export default AInterface
注意init()上面方法的使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/389837.html
標籤:javascript 节点.js 界面 多重继承 ts-混合器
