4

So I would like to call an es 6 static class method By reflection using a string className and a string method name. 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.

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);
J.V.
  • 165
  • 2
  • 7

2 Answers2

3

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:

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.

Adelin
  • 7,809
  • 5
  • 37
  • 65
-2

You're setting your variables to strings instead of the reference to your objects.

hdennen
  • 57
  • 8
  • yes that is true and that is just the problem i like to solve I will get the strings for attributes out of my dom I'll edit my question to make this more clear thanks – J.V. Feb 01 '18 at 09:11