Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function whose name is stored in a variable [duplicate]

Tags:

javascript

I have the following script:

(function () {
    var Module = (function () {
        var fctToCall = function () {
            alert('Foo');
        };
        return {
            fctToCall: fctToCall
        };
    })();
    var Module2 = (function () {
        var init = function () {
            var str = 'fctToCall';
            Module.str(); // here
        };
        return {
            init: init
        };
    })();
})();

So I want to call this fctToCall method by its name - how can I do that? So far I know 3 methods:

  • by attaching the function to the window object, but then it wouldn't be local and in closure, and I wouldn't have the access to other local variables
  • eval, the best options as far as I see it, but it's still eval, so I don't wanna use it
  • this, but it's another architecture, I don't wanna change it

How can I solve this?

like image 997
user99999 Avatar asked Nov 23 '15 11:11

user99999


People also ask

How do you call a function stored in a variable?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

Can we store a function name in a variable and then invoke it via a variable?

So, it is possible to store a named function inside a variable, but we still can only call the function by the variable name.

How do you call a function assigned to a variable in JavaScript?

Syntax. Users can follow the below syntax to write the expression for the arrow function. const variable = ( … parameters ) => { // function body } Variable( parameters ); // invoke the arrow function.

What happens if you define a variable that has the same name as a built in variable?

It will no longer refer to it's original global built-in function, even though you assign a new value at the end of the function. You must be getting this error too.


1 Answers

To call function use

Module[str]();

As Module is an object, you can access the dynamic properties and methods of it by using the bracket notation.

(function() {
  var Module = (function() {
    var fctToCall = function() {
      console.log('Foo');
    };
    return {
      fctToCall: fctToCall
    };
  })();
  var Module2 = (function() {
    var init = function() {
      var str = 'fctToCall';
      
      // Call as
      Module[str]();
    };
    return {
      init: init
    };
  })();

  Module2.init();
})();
like image 70
Tushar Avatar answered Sep 30 '22 01:09

Tushar