[英]JavaScript: How to get child Class's methods in parent's constructor?
How to get ( console.log
for ex.) B
class's methods in A
class's constructor? 如何在
A
类的构造函数中获取(例如, console.log
) B
类的方法?
class A {
constructor() {
// GET B's method names ('ok', ...) here
}
}
class B extends A {
constructor() {
super();
}
ok() {
}
}
Use either new.target.prototype
or Object.getPrototypeOf(this)
to get the prototype object of the instantiated subclass. 使用
new.target.prototype
或Object.getPrototypeOf(this)
获取实例new.target.prototype
类的原型对象。 Then traverse the prototype chain to all superclasses, and get the own properties of each object. 然后遍历原型链到所有超类,并获得每个对象的自身属性。 Don't forget non-enumerable properties.
不要忘记不可枚举的属性。
Of course, using this in a constructor for more than logging/debugging purposes is a code smell. 当然,在构造函数中将此功能用于日志记录/调试之外的其他事情也是一种代码味道。 A class should not need to know about its subclasses.
一个类不必了解其子类。 If you want to do autobindings, let each subclass constructor autobind its own methods.
如果要进行自动绑定,请让每个子类构造函数自动绑定其自己的方法。
In the "base" constructor you have access to complete object, so can check what is its real constructor and so its prototype const childClassPrototype = this.constructor.prototype
. 在“基本”构造函数中,您可以访问完整的对象,因此可以检查其真正的构造函数是什么,因此可以检查其原型
const childClassPrototype = this.constructor.prototype
。 Having a "child" prototype you can get a list of its properties with Object.getOwnPropertyNames(childClassPrototype)
. 拥有一个“子”原型,您可以使用
Object.getOwnPropertyNames(childClassPrototype)
获得其属性列表。 From that list you want to filter out "constructor" and properties that are not functions. 您要从该列表中过滤掉“构造函数”和不是函数的属性。
Note: this technique will only give you access to "leaf" prototype, once you may have a multi level prototype chain. 注意:一旦您拥有多级原型链,此技术将仅使您能够访问“叶子”原型。 Thus you have to iterate over prototype chain.
因此,您必须遍历原型链。
Note2: for autobinding you may like to consider using a decorator. 注意2:对于自动绑定,您可能想考虑使用装饰器。 One implementation is here: https://github.com/andreypopp/autobind-decorator - this technique gives you better control over unexpected behavior that may come from metaprogramming
一种实现方式在这里: https : //github.com/andreypopp/autobind-decorator-此技术使您可以更好地控制可能来自元编程的意外行为
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.