J.V.
J.V.

Reputation: 165

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. 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);

Upvotes: 4

Views: 50

Answers (2)

Adelin
Adelin

Reputation: 8219

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.

Upvotes: 3

hdennen
hdennen

Reputation: 57

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

Upvotes: -2

Related Questions