Question

I am trying to call a function whose name is defined elsewhere is the code.

Below is sample code:

Inner.testFunc = function(node) { 
 var functionName = node.substring(node, to.indexOf('@'));
 // call the function based on functionName
 [functionName + '()']
}

function something() {
 //doing something
};

...

Assuming that functionName = something, this should try to call the function, but it isn't doing it.

I'm tried using other links such as Call javascript function which name is in variable but it didn't help.

I've also tried using eval():

eval(functionName + '()');

but this returned something about an illegal character...

Was it helpful?

Solution

Your eval call might not be working; use instead:

eval(functionName)(); //note () after the eval statement

In your code ensure first that functionName is something

console.log(functionName === 'something') //true

OTHER TIPS

If your function is defined in the global scope, you could take advantage of the fact that global variables and global functions can be accessed as properties of the global scope:

function something(){ console.log('Works!'); }
window['something'](); // Works!

If it is not, perhaps a reference to it is stored as a property of an object:

var x = { something : function(){ console.log('Also works'); } };
x['something'](); // Also works

Otherwise, it is impossible to access.

functionName is the return of the substring method, not the function itself.

You can create a map of functions with their names as keys as shown below. And then you can pass the output of substring to the map and call the function.

function myName() {
    console.log("thefourtheye");
}

var functions = {             // map of functions and their names
    name: myName
};

functions["name"]();          // Instead of "name" pass the result of substring

It's a little more verbose but what about using a case statement to run a function based on the value of node.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top