【问题标题】:Implement an interfaces with multiple inheritance in a Nodejs class在 Nodejs 类中实现具有多重继承的接口
【发布时间】:2022-01-23 14:32:31
【问题描述】:

我尝试了以下方法来创建接口并实现它。

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

【问题讨论】:

    标签: javascript node.js interface multiple-inheritance ts-mixer


    【解决方案1】:

    问题似乎是AInterface的构造函数没有得到正确的this。所以它看不到methodAmethodB

    解决方法是避免在构造函数中进行检查。

    import AInterface from "./AInterface.mjs";
    import { Mixin, settings } from "ts-mixer";
    
    settings.initFunction = "init";
    
    class ClassA extends Mixin(AnotherClass, AInterface) {}
    

    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()方法的使用。

    【讨论】:

    • 如果构造函数没有得到正确的this 值,这听起来很像ts-mixer 库中的错误?
    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 2011-11-21
    • 2011-10-07
    • 2012-04-26
    • 2013-10-22
    • 2019-03-06
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多