@thatcompany/ts-tool
Version:
基于TypeScript编写的工具库
88 lines • 2.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Clazz = void 0;
class Clazz {
/**
* 判断类型的最祖先类是否是指定类
* @param child 子类
* @param ancestor 祖类
*/
static isClassFromAncestor(child, ancestor) {
let proto = Object.getPrototypeOf(new child());
while (proto) {
if (proto === ancestor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
/**
* 判断类型是否继承链是否包含某个父类
* @param child 子类
* @param parent 父类
*/
static hasClassInChain(child, parent) {
// 先判断是否是同一个类
if (child === parent) {
return true;
}
// 再判断是否是子类
let proto = Object.getPrototypeOf(child.prototype);
while (proto) {
if (proto === parent.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
/**
* 获取类的所有字段名列表
* @param target 类
*/
static getClassAllField(target) {
const instance = new target();
// @ts-ignore
const allKeys = Reflect.ownKeys(instance);
// @ts-ignore
return allKeys.filter((key) => typeof instance[key] !== 'function');
}
/**
* 获取类的所有方法名列表(包括继承的方法)
* @param target 类
*/
static getClassAllMethod(target) {
const instance = new target();
const methodNames = new Set();
let proto = Object.getPrototypeOf(instance);
while (proto && proto !== Object.prototype) {
const keys = Reflect.ownKeys(proto);
keys.forEach((key) => {
// 过滤出函数类型的方法名,并确保不包含构造函数名
if (typeof instance[key] === 'function' && key !== 'constructor') {
methodNames.add(key);
}
});
proto = Object.getPrototypeOf(proto);
}
return Array.from(methodNames);
}
/**
* 获取类的所有静态字段名列表
* @param target 类
*/
static getClassStaticField(target) {
return Reflect.ownKeys(target);
}
/**
* 获取类的所有静态方法名列表
* @param target 类
*/
static getClassStaticMethod(target) {
const keys = Reflect.ownKeys(target);
return keys.filter((key) => typeof target[key] === 'function' && key !== 'prototype');
}
}
exports.Clazz = Clazz;
//# sourceMappingURL=Clazz.js.map