typescript如何获取一个类的所有公有方法不使用第三方库
可以使用反射来获取一个类的所有公有方法。具体步骤如下:
- 获取类的构造函数。
const constructor = MyClass.constructor;
- 使用
Object.getOwnPropertyNames()方法获取类的所有属性,包括方法和属性。
const properties = Object.getOwnPropertyNames(constructor.prototype);
- 使用
Array.filter()方法过滤出所有公有方法。
const publicMethods = properties.filter((property) => {
return typeof constructor.prototype[property] === "function" && property !== "constructor";
});
完整的代码如下:
class MyClass {
public myMethod1() {
console.log("myMethod1");
}
public myMethod2() {
console.log("myMethod2");
}
private myPrivateMethod() {
console.log("myPrivateMethod");
}
}
const constructor = MyClass.constructor;
const properties = Object.getOwnPropertyNames(constructor.prototype);
const publicMethods = properties.filter((property) => {
return typeof constructor.prototype[property] === "function" && property !== "constructor";
});
console.log(publicMethods); // ["myMethod1", "myMethod2"]
``
原文地址: http://www.cveoy.top/t/topic/hxHz 著作权归作者所有。请勿转载和采集!