javascript – Call a function inside another, through a string


To facilitate the work of other programmers in the company whose default is not to have a pattern , I created a JavaScript library with some formatting and form field validation functions (date, phone, CPF, CNPJ, etc.).

At the end of the process, this library allowed me a very simple call:

<input type="[data|telefone|...]" name="" value="">

At the end of the page load I generate a NodeList and assign the appropriate functions to each input according to its type .

The code then looked like this:

The problem with the method used is that even though only one of the functions is being executed for each input (as it should be), I am setting ALL the functions for each object found in my NodeList . That is, for each object I have a kilometric code, containing several functions that this object will never use.

On normal pages, where this feature is not used much, the problem is completely imperceptible. However, on pages where these functions are called numerous times, it is possible to notice a certain loss of performance after loading the page.
And, since the company's system is also intended to be used on mobile devices, a small loss of performance can end up becoming a big problem.

To solve this, I thought of isolating each of the functions. Here's my problem!
I have N functions ( date, phone, cpf, … ), inside a global function ( setEvents ) and all I have to call these internal functions is their name in string form.

I've already tried in several ways, but with no success.
The only way that worked so far was using eval . But, as JS Bin says: " eval is evil. "


Just a suggestion, you can put the functions inside an object, and call it by name:

  function a() {
    var nomeDaFuncao = [função a ser chamada];

    var fncObj = {
        b: function(objeto) {
         . . .

        c: function(objeto) {
         . . .


But it would be much better if you explain the reason for this strange logic… because even the way I said it, it sounds kind of strange to me to have something like that… wouldn't a switch solve it?

Scroll to Top