javascript - 如何使用在别处定义的函数来定义 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
}
// ...
}
我想知道如何someMethod
用useMyMethod(this)
.
谢谢您的帮助!
解决方案
推荐阅读
- c++ - B+ 键的树数据结构
- javascript - ReferenceError: jsPDF 未定义(可以访问包)
- javascript - 如何使用 discord.js 创建用于创建语音通道的侦听器?
- windows-subsystem-for-linux - Windows Insider Preview 版本上的 WSLG - 无法加载 gui 应用程序
- python - Python 程序无法识别输入
- c++ - c++/openGL - 类/对象中的 VBO/VAO 代码根本不呈现
- php - PHP用没有foreach循环的随机字符替换字符串中的特定字符
- python - odoo-14:当我尝试使用 Digital Ocean 安装模块时出现错误
- ios - 如何从某些结果中过滤随机字符串生成器
- bash - 从单个命令的多行输出中读取多个变量