Variable functions in javascript

4

In PHP we have the variable functions , which basically allow us to do this among other things

class Bar
{

    function __construct($foo)
    {
        $this->{'funcion' . $foo}();
    }

    private function funcionHola()
    {
        echo "Hola!";
    }

    private function funcionAdios()
    {
        echo "Adios!";
    }
}

$barHola = new Bar('Hola');
echo "<br />";
$barAdios = new Bar('Adios');

And it will print this:

Hola!
Adios!

Is there a way to do this in javascript? I mean to dynamically call a function or method

I have this code in javascript, and in load() I want to call the variable function

(function(window, document) {
  'use strict';

  var Bar = {
    load: function(foo) {
      // Llamar a la función variable
    },

    funcionHola: function() {
      console.log('Hola');
    },

    funcionAdios: function() {
      console.log('Adios');
    }
  };

  Bar.load('Hola');
  Bar.load('Adios');
}(window, window.document));
    
asked by KacosPro 03.02.2018 в 04:50
source

3 answers

3

You can do it depending on the scope that you are using to call the function, assuming that we are within a global scope you could use:

window['nombredelafuncion'](); replacing nombredelafuncion with a string variable with the name of the function you want to call.

    
answered by 04.02.2018 / 01:00
source
4

In this case, you can call your functions through this['funcion' + foo](); because the functions are within a scope, in this case the object.

Therefore, these functions are only defined within the scope of the object, and not in the global scope of the application. You can try to call one of these functions directly outside the object and you will see how it does not leave you if you do not refer to the object (scope) that contains them.

By means of the reserved word this you refer to the object itself since you are calling it within it.

Your modified example:

(function(window, document) {
  'use strict';

  var Bar = {
    load: function(foo) {  
      this['funcion' + foo]();
    },

    funcionHola: function() {
      console.log('Hola');
    },

    funcionAdios: function() {
      console.log('Adios');
    }
  };

  Bar.load('Hola');
  Bar.load('Adios');
}(window, window.document));
    
answered by 03.02.2018 в 13:21
2

You can do the following:

var myFunc = {

    'funOne': function(){

         return "this is funOne";

    },

    'funTwo': function() {
        return " this is fun two;
    }
}

Then you call her:

var x = myFunc['funOne'];

In your case it would be like this:

var x = Bar['funcionHola'];

You can also see this post

    
answered by 03.02.2018 в 14:16