如果您只需要获取 getter/setter,那么您需要执行以下操作:
class Test {
...
public static getGetters(): string[] {
return Object.keys(this.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.prototype, name)["get"] === "function"
});
}
public static getSetters(): string[] {
return Object.keys(this.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.prototype, name)["set"] === "function"
});
}
}
Test.getGetters(); // ["RowsCount", "RowsCount2"]
Test.getSetters(); // ["RowsCount", "RowsCount2"]
(code in playground)
您可以将静态方法放在基类中,然后当您扩展它时,子类也将具有这些静态方法:
class Base {
public static getGetters(): string[] {
return Object.keys(this.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.prototype, name)["get"] === "function"
});
}
public static getSetters(): string[] {
return Object.keys(this.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.prototype, name)["set"] === "function"
});
}
}
class Test extends Base {
...
}
Test.getGetters(); // work the same
(code in playground)
如果您希望这些方法成为实例方法,那么您可以这样做:
class Base {
public getGetters(): string[] {
return Object.keys(this.constructor.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.constructor.prototype, name)["get"] === "function"
});
}
public getSetters(): string[] {
return Object.keys(this.constructor.prototype).filter(name => {
return typeof Object.getOwnPropertyDescriptor(this.constructor.prototype, name)["set"] === "function"
});
}
}
变化在于,您使用的是this.constructor.prototype,而不是this.prototype。
那么你只需:
let a = new Test();
a.getGetters(); // ["RowsCount", "RowsCount2"]
(code in playground)
编辑
基于@Twois 的评论,他指出在以 es6 为目标时它不起作用,这是一个可以工作的版本:
class Base {
public static getGetters(): string[] {
return Reflect.ownKeys(this.prototype).filter(name => {
return typeof Reflect.getOwnPropertyDescriptor(this.prototype, name)["get"] === "function";
}) as string[];
}
public static getSetters(): string[] {
return Reflect.ownKeys(this.prototype).filter(name => {
return typeof Reflect.getOwnPropertyDescriptor(this.prototype, name)["set"] === "function";
}) as string[];
}
}
主要区别:使用Reflect.ownKeys(this.prototype) 而不是Object.keys(this.prototype)。