Calling a static method by name as string in Javascript

Asked

Viewed 120 times

1

If I want to call a static function by name as string, how do I?

I did what is below, suppose the function name is "move".

class Transformation {
    static operate(object, function_name) {
          eval(function_name)(object);
    }
    static move(object) {... some code...}
}

But it didn’t work.

NOTE: I am calling this function from another file in the same directory.

  • 1

    I translated the question into Portuguese. But the warning: usually the questions that are posted in English on this site are quickly closed.

1 answer

2


I’m not sure I understand what you want, but maybe this is it:

class Transformation {
    static operate(function_name, object) {
        Transformation[function_name](object);
    }
    static move(object) { alert("oi " + object); }
}

Transformation.operate("move", "teste");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.