Call one function inside the other, through a string

6

In order to make it easier for other programmers to default to , I have created a JavaScript library with some form field validation and formatting functions (date, telephone, 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 page load I generate a NodeList and assign the appropriate functions for each input according to its type .

This code then looks like this: JSBin.com

The problem with the method used is that although only one of the functions is being executed for every input (as it should be), I'm setting ALL functions for each object found in my NodeList . That is, for each object I get a kilometer code, containing several functions that this object will never use.

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

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

I've tried it in many ways, but I did not succeed. The only way it worked so far was to use eval . But as the JS Bin says: " eval is evil. "

    
asked by anonymous 31.03.2014 / 21:38

4 answers

5

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

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

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

        c: function(objeto) {
         . . .
        }
    }

    fncObj[nomeDaFuncao](objeto);
  }
</script>

But it would be much better if you explain the reason for this strange logic ... because even the way I said, it sounds kind of weird having something like that ... does switch not solve? >     

31.03.2014 / 21:50
2

You can use namespace for this. An object with several functions where it calls the function that needs and does not pollute the global space as in its original idea.

var validar = {

    date: function (value) {
        return [value, 'Função para data'];
    },
    text: function (value) {
        return [value, 'Função para texto'];
    },
    password: function (value) {
        return [value, 'Função para passwords'];
    }
}

And then you can use it like this:

// "el" no exemplo é o elemento que quer analisar
var type = el.getAttribute("type");
var retornoFuncao = validar[type](el.value);

Example

I used the same code inside each function but I imagine you wanted to adapt that part.

    
01.04.2014 / 05:47
2

Hello, try doing this:

function a(){
    alert('olá a');
    var nomeFuncao = 'b';
    var b = function(){
        alert('olá b');
    };

    var c = function(){
        alert('olá c');
    };

    eval(nomeFuncao)();
}

JS Bin

You can also use this alternative without eval() :

func_a = function(arg1) {
    alert('call a '+ arg1);
};
func_b = function() {
    alert('b');
};
func_c = function() {
    alert('c');
};

var n = "a";

 window["func_" + n]('arg1');

JS Fiddle

Another option using Jquery:

$.main = {
    a : function(arg){
        alert('function a - arg: '+arg);
    },
    b : function(){
        alert('b');
    },
    c : function(){
        alert('c');
    },
    call : function(func,arg){
        $.main[func](arg);
    }
};
$.main.call('a','param 1');
$.main.call('b');
$.main.call('c');

With Jquery

    
31.03.2014 / 22:39
1

Try to explicitly add your functions to the window object as here :

window.dyna = function(param) {
    alert("dyna " + param);
}
window["dyna"]("oi");

Some browsers do not even need this and it would work the way you did.

Edit 1

Testing here does not work in your example because the b() and c() functions are not directly on the window object. Therefore they are not found in the scope of window

Since they are created in the scope of function a() , they will only exist within function a() , and if within a() you want to access b() , for example, you have to do something like this:

this["b"]();
// que é o mesmo que this.b();

Edit 2

To use this , as I mentioned you have to do something like this, your problem is scope, so you have to attach your function to an object that is accessible in the scope where you intend to call it, in case the this , as follows in the sample code:

function a(nomeDaFuncao) {

  // anexa a function "b" ao objeto local this
  this.b  = function(param) {
      alert("b " + param);
  }

  // anexa a function "c" ao objeto local this
  this.c = function(param) {
      alert("c " + param);
  }

  // chama a function pelo nome no objeto local this
  this[nomeDaFuncao]("oi");
}

a(nomeDaFuncao);

Example here

To understand a little better how the scope of objects works in the , I recommend this which is very good and this from MDN .

  

Note: I do not know what your real problem is in order to need such a solution, but whatever it may be, there may be simpler and cleaner ways to do it, but this solution will work for your current issue.

    
31.03.2014 / 21:51