在构造函数中保存扩展 class' 方法的名称
Save extending class' methods' names in constructor
我有三个 classes,其中两个扩展了第三个。是否有可能以某种方式(不同于手动)将扩展 classes 的名称分配给超级构造函数?
class Master {
constructor(options) {
this.methods = Object.getOwnPropertyNames( Master.prototype );
}
getMethods() {
return Object.getOwnPropertyNames( Master.prototype );
}
}
class SlaveOne extends Master {
constructor(options) {
super(options);
}
methodOne() {}
methodTwo() {}
}
class SlaveTwo extends Master {
constructor(options) {
super(options);
}
methodThree() {}
methodFour() {}
}
所以,我想要的是在 Master class 中有方法或 this.methods
赋值,这将:
- return
['constructor', 'methodOne', 'methodTwo']
在 SlaveOne
; 的实例上调用时
- return
['constructor', 'methodThree', 'methodFour']
在 SlaveTwo
; 的实例上调用时
当在 SlaveOne
、SlaveTwo
或 Master
的实例上调用时,我当前的代码将 return 相同 ['constructor', 'getMethods']
。有什么想法吗?
像这样应该可以解决问题
class Master {
getMethods() {
return Object.getOwnPropertyNames( this.constructor.prototype );
}
}
class SlaveOne extends Master {
constructor(options) {
super(options);
}
methodOne() {}
methodTwo() {}
}
class SlaveTwo extends Master {
constructor(options) {
super(options);
}
methodThree() {}
methodFour() {}
}
console.log(new SlaveOne().getMethods(), new SlaveTwo().getMethods())
我有三个 classes,其中两个扩展了第三个。是否有可能以某种方式(不同于手动)将扩展 classes 的名称分配给超级构造函数?
class Master {
constructor(options) {
this.methods = Object.getOwnPropertyNames( Master.prototype );
}
getMethods() {
return Object.getOwnPropertyNames( Master.prototype );
}
}
class SlaveOne extends Master {
constructor(options) {
super(options);
}
methodOne() {}
methodTwo() {}
}
class SlaveTwo extends Master {
constructor(options) {
super(options);
}
methodThree() {}
methodFour() {}
}
所以,我想要的是在 Master class 中有方法或 this.methods
赋值,这将:
- return
['constructor', 'methodOne', 'methodTwo']
在SlaveOne
; 的实例上调用时
- return
['constructor', 'methodThree', 'methodFour']
在SlaveTwo
; 的实例上调用时
当在 SlaveOne
、SlaveTwo
或 Master
的实例上调用时,我当前的代码将 return 相同 ['constructor', 'getMethods']
。有什么想法吗?
像这样应该可以解决问题
class Master {
getMethods() {
return Object.getOwnPropertyNames( this.constructor.prototype );
}
}
class SlaveOne extends Master {
constructor(options) {
super(options);
}
methodOne() {}
methodTwo() {}
}
class SlaveTwo extends Master {
constructor(options) {
super(options);
}
methodThree() {}
methodFour() {}
}
console.log(new SlaveOne().getMethods(), new SlaveTwo().getMethods())