简体   繁体   English

如何从 javascript 中的方法引用中检索 class?

[英]How can I retrieve a class from a method reference in javascript?

I would like to do this:我想这样做:

function call(method) {
    const object = // Retrieve the class that declares the method and then construct an instance dynamically.
    method.call(object) // So 'this' is bound to the instance.
}

call(MyClass.prototype.myMethod)
call(AnOtherClass.prototype.anOtherMethod)

My goal is to create the instance from a dependency container.我的目标是从依赖容器创建实例。 That's why the method has to be bound to an instance that will have all the dependencies required by the class.这就是为什么该方法必须绑定到一个实例,该实例将具有 class 所需的所有依赖项。

You can't do this automatically without some restructuring.如果不进行一些重组,您将无法自动执行此操作。 If it were me, I'd pass the class as an argument:如果是我,我会将 class 作为参数传递:

function call(theClass, method) {
  const instance = new theClass();
  method.call(instance);
}
call(MyClass, MyClass.prototype.myMethod)
call(AnOtherClass, AnOtherClass.prototype.anOtherMethod)

or, you could pass just the prototype method names for the second argument:或者,您可以只为第二个参数传递原型方法名称:

function call(theClass, method) {
  const instance = new theClass();
  instance[method]();
}
call(MyClass, 'myMethod')
call(AnOtherClass, 'anOtherMethod')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM