Javascript dynamically call function from string

Can I dynamically call an object method having the method name as a string? I would imagine it like this:

var FooClass = function() {
    this.smile = function() {};
}

var method = "smile";
var foo = new FooClass();

// I want to run smile on the foo instance.
foo.{mysterious code}(); // being executed as foo.smile();

asked Mar 24, 2012 at 19:51

Mikulas DiteMikulas Dite

7,6299 gold badges57 silver badges97 bronze badges

if the name of the property is stored in a variable, use []

foo[method]();

answered Mar 24, 2012 at 19:55

Karoly HorvathKaroly Horvath

92.6k11 gold badges113 silver badges173 bronze badges

4

Properties of objects can be accessed through the array notation:

var method = "smile";
foo[method](); // will execute the method "smile"

answered Mar 24, 2012 at 19:55

0

When we call a function inside an object, we need provide the name of the function as a String.

var obj = {talk: function(){ console.log('Hi') }};

obj['talk'](); //prints "Hi"
obj[talk]()// Does not work

answered Dec 24, 2018 at 17:44

s.ns.n

6631 gold badge9 silver badges17 bronze badges

2

method can be call with eval eval("foo." + method + "()"); might not be very good way.

answered Mar 24, 2012 at 20:04

1

I would like to leave an example here for this. For example; i want to call a dynamically check method while submitting the form.

$('form').on('submit', function(e){

    var beforeSubmit = $(this).attr('data-before-submit');

    if( beforeSubmit ){

       params = beforeSubmit.split(".");
       objectName = params[0];
       methodName = params[1];

       result = window[objectName][methodName]($(this));

       if( result !== true ){
           e.preventDefault();
       }

    }

});

var MyObject = {
    myMethod = function(form){
        console.log('worked');
        return true;
    }
};

answered May 8, 2020 at 23:43

Javascript dynamically call function from string

ahmetiahmeti

3254 silver badges9 bronze badges

eval is evil in JavaScript! The MDN eval page states:

Obsolete
This feature is obsolete. Although it is still supported by browsers, its usage is discouraged in new projects. Try to avoid using it.

eval executes a string containing code, e.g.

eval("var x = 'Hello from eval!';");
console.log(x);

eval raises several issues:

  1. Security: your string can be injected with other commands by third-party scripts or user input.
  2. Debugging: it’s difficult to debug errors — you have no line numbers or obvious points of failure.
  3. Optimization: the JavaScript interpreter cannot necessarily pre-compile the code because it could change. While interpreters have become increasingly efficient, it’ll almost certainly run slower than native code.

Unfortunately, eval is very powerful and it’s easy for less experienced developers to overuse the command.

Despite the warnings, eval still works — even in Strict Mode — but you can normally avoid it. In the past it was primarily used for de-serializing JSON strings but we now have the safer JSON.parse method.

However, what if we have a function name in a string, e.g.

// function we want to run
var fnstring = "runMe";

function runMe() {
	// do stuff
}

How do we execute the runMe() function without using eval? I recently encountered this situation when using the HTML5 History API; the pushState method won’t permit you to store a direct reference to a function so you need to define its name as a string. You could also face similar challenges using Web Workers or any other API where objects are serialized.

The simplest and safest execution-without-eval solution is a range of conditions, e.g.

// function we want to run
var fnstring = "runMe";

switch (fnstring) {
	case "functionX": functionX(); break;
	case "functionY": functionY(); break;
	case "functionZ": functionZ(); break;
	case "runMe": runMe(); break;
}

It’s safe, but fairly inefficient and painful to write if you have dozens of possible function calls.

A better solution is to use the window object which references the current window and all items within it. We can check whether fnstring is available as an object within window and run it if it’s a function, e.g.

// function we want to run
var fnstring = "runMe";

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn();

You can perform other checks if necessary to ensure the function has an expected name.

What if the function we want to call has parameters — perhaps stored in an array? No problem; we simply use the apply method:

// function name and parameters to pass
var fnstring = "runMe";
var fnparams = [1, 2, 3];

// find object
var fn = window[fnstring];

// is object a function?
if (typeof fn === "function") fn.apply(null, fnparams);

So that’s another reason to stop using eval. As a bonus, this solution is safer, less error prone, easier to debug and will normally execute faster. I hope it helps.

How do you call a function from a string in JavaScript?

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.

How do you call a function dynamically?

To call a the function dynamically, all you have to do is creating an instance of the class you're in and call the function using the dynamic instance created. For example, we have a class and a function: class Ersoy.

How to call a function using variable in JavaScript?

The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

How do you call a function name?

Define a function named "myFunction", and make it display "Hello World!" in the

element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.