【问题标题】:How can I retrieve a class from a method reference in javascript?如何从 javascript 中的方法引用中检索类?
【发布时间】:2021-02-26 21:26:45
【问题描述】:

我想这样做:

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)

我的目标是从依赖容器创建实例。这就是为什么该方法必须绑定到一个实例,该实例将具有该类所需的所有依赖项。

【问题讨论】:

  • 是否也传入对象?
  • 与其他具有class 系统的语言不同,在 JavaScript 中,方法和声明它们的类之间没有永久关系。
  • 是的,我将传递类对象以及@CertainPerformance 提到的方法

标签: javascript class reflection introspection


【解决方案1】:

如果不进行一些重组,您将无法自动执行此操作。如果是我,我会把这个类作为参数传递:

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

或者,您可以只为第二个参数传递原型方法名称:

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

【讨论】:

  • 是的,这就是我的计划。我只是有一个 TS 的打字问题。我怎样才能强制该方法静态地成为类的一部分?不过,这可能是一个独立的问题
  • 注意潜在的限制:当不提供参数时,并非所有构造函数都能正常工作。这是基本的,我很确定。可能没有完全通用的技术可以在这里工作。但这可能不会影响 OP 的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 2022-12-11
  • 2014-05-29
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多