简体   繁体   English

ecmascript 6如何通过反射调用静态类方法

[英]ecmascript 6 how to call a static class methode by reflection

So I would like to call an es 6 static class method By reflection using a string className and a string method name. 所以我想通过反射使用字符串className和字符串方法名称来调用es 6静态类方法。 I have tried several ways. 我尝试了几种方法。 unfortunately I don't seem to find the correct way to do this. 不幸的是,我似乎没有找到正确的方法来做到这一点。

By the way (as mentioned in the comments below) I am looking for a solution where I will get the name of the class and the name of the method from dom attributes so they need to be a string. 顺便说一句(如下面的评论中所述),我正在寻找一种解决方案,将从dom属性中获取类的名称和方法的名称,因此它们必须是字符串。

Can anybody help? 有人可以帮忙吗?

 class a{ static b(nr){ alert('and the answer is' + nr) } } let aClassName = 'a', aMethodeName = 'b', theCompleteCall = 'a.b', anArgument = 42; //Reflect.apply(theCompleteCall,anArgument); //window[aClassName][aMethodeName](anArgument); //window[theCompleteCall](anArgument); 

Because of the fact that let and class not being declared in a global scope as you'd expect ( read more ), you need to declare your class in a scope accessible, like so: 由于letclass并没有像您期望的那样在全局范围内声明( 更多内容 ),因此您需要在可访问的范围内声明您的类,如下所示:

window.a = class a{
    static b(nr){
    alert('and the answer is' + nr)
  }
}

let aClassName = 'a',
        aMethodeName = 'b',
    theCompleteCall = 'a.b',
    anArgument = 42;

Then, you can call with reflection, like so: 然后,您可以进行反射调用,如下所示:

window[aClassName][aMethodeName](anArgument)

So, the solution, is to provide a scope when declaring them, and access them through that scope. 因此,解决方案是在声明它们时提供范围,并通过该范围对其进行访问。

您正在将变量设置为字符串,而不是对对象的引用。

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

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