首页 > 解决方案 > 如何使用在别处定义的函数来定义 Javascript 类静态方法?

问题描述

我有一个这样定义的 Javascript 类(env:node.js v12 或更高版本):

module.exports = class MyClass extends SomeOtherClass {

// ...

  static async someMethod() {
    const result = await this.exampleSuperMethod()
  return result
}

// ...

}

我正在扩展SomeOtherClass,它定义了一个名为 的静态方法,如上所述exampleSuperMethod,该方法在 my 中使用。someMethod

现在,我想someMethod通过使用在其他地方定义的函数来定义方法。这是必需的,因为该函数是通用的,我不想在我的类中重复相同的代码。此外,在外部模块中定义函数,我可以只测试一次,并在任何地方重用我共享和测试的代码。

为了实现这一点,我想定义一个函数,如下所示:

const myMethod = (MainClass) => async () => {
  const result = await MainClass.exampleSuperMethod({
    // do something
  })
  return result
}

module.exports = myMethod

在这个函数中,我通过导出一个用闭包定义我需要的函数的高阶函数来允许MainClass(需要到达)的依赖注入。exampleSuperMethod使用这样定义的类,我将能够简单地模拟“main”SomeOtherClass并将其传递给高阶函数 this mock,它公开了exampleSuperMethod. 在实际使用中,我的想法是注入this元素并取回准备好作为静态方法插入到我的类中的函数。但我不确定如何实现最后一点。

我的主要课程可能会变成以下内容:

const useMyMethod = require('./path-to-file/my-method.js')

module.exports = class MyClass extends SomeOtherClass {

// ...

  // how to replace the following to use the 
  // function received by the call to 
  // useMyMethod(this) ?
  //
  static async someMethod() {
    const result = await this.exampleSuperMethod()
  return result
}

// ...

}

我想知道如何someMethoduseMyMethod(this).

谢谢您的帮助!

标签: javascriptnode.js

解决方案


推荐阅读