javascript - 获取具有特定参数的对象的方法
问题描述
TypeScript 中有没有办法获取具有特定参数的类中的所有方法?
我正在尝试围绕此编写 UnitTest。
例如
class Foo {
constructor() { ... }
set blah(b) { ... }
get blah() { ... }
method1(yes : any) { ... }
method2(no : any) { ... }
method3(yes : any) { ... }
method4(no : any, not : any, this : any) { ... }
}
这个想法应该是获取 Foo 中的所有方法,其中有一个名为“yes”的有效负载。我也有一个类名的字符串形式。
所以在这种情况下,它应该是一个数组[method1, method3]
,我可以在我的单元测试中循环。
这是我到目前为止得到的:
let className = 'Foo' // Assume that this is given
let methodNames = Object.getOwnPropertyNames(Object.getPrototypeOf(className))
methodNames.filter((x) => x !== <stuck here>).forEach((m) => { .. }
我不想做这样的事情。好奇是否有更简单的方法。
我也看过这个页面:如何动态获取函数参数名称/值?
但在我的情况下不起作用,因为我的 className 是字符串格式。
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
var fnStr = func.toString().replace(STRIP_COMMENTS, '');
var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
if(result === null)
result = [];
return result;
}
let className = 'Foo' // Assume that this is given
let methodNames = Object.getPrototypeOf(className)
console.log(getParamNames(methodNames)) // Returns [Object, Object] also tried just className didn't work.
解决方案
推荐阅读
- templates - pandoc 和 markdown 替换宏
- html - 我无法让@keyframes 填充超过 180 度以停止我想要的位置
- google-cloud-dataflow - Apache Beam:如何返回多个输出
- arrays - 在 Fortran 中读取具有多种类型的数组时出现问题
- python - 存储在 GCS 存储桶中时无法重命名文件
- python - ADX、KQL 和熊猫
- javascript - Django 和 Axios 被禁止(CSRF 令牌丢失或不正确。)
- perl - Perl 的 -d 开关中断
从表单的 POST 中读取 - python - 如何设置 vimrc 配置,使其自动缩进 4 个空格而不是制表符?
- c# - 升级到 Visual Studio 16.11.1 后,Xamarin Forms 破坏了 XALNS7028:System.IO.FileNotFoundException:无法加载程序集“Xamarin.iOS”