Calling a JavaScript function named in a variable
I'd avoid eval.
To solve this problem, you should know these things about JavaScript.
- Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
- If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
- Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot
.
rather than square brackets[]
, or vice versa.
Your problem is a result of considering the dot manner of reference rather than the square bracket manner.
So, why not something like,
window["functionName"]();
That's assuming your function lives in the global space. If you've namespaced, then:
myNameSpace["functionName"]();
Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.
JavaScript call function inside a function by variable name
There is no sensible way of accessing an arbitrary variable using a string matching the name of the variable. (For a very poor way to do so, see eval
).
[x]();
// DOESN'T WORK
You're trying to call an array as a function
NEITHER
this[x]()
The function isn't a property of the inner
object.
window[x]()
, etc.
Since it isn't a global, it isn't a property of the window object either.
If you need to call a function based on the value of a string variable, then organise your functions in an object and access them from that.
function b() {
alert('got it!');
}
var myFunctions = {
b: b
};
x = 'b';
myFunctions[x]();
Call a function whose name is stored in a variable
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();})();
Is it possible to call a function with a variable?
You can call it from the window
object.
The window object in HTML 5 references the current window and all items contained in it. Hence we can use it to run a function in a string along with parameters to the function.
$(function(){
$("a").click(function() {
var call = $(this).attr('data-value')
window[call]();
});
});
You can do it by using eval()
too. But note, the eval()
method is older and it is deprecated.
$(function(){
$("a").click(function() {
var call = $(this).attr('data-value')
eval(call)();
});
});
Storing named function in a variable with a different name
When you use a named function expression (NFE) like that, the function's name is only in scope within the function:
var x = function z(){ console.log(typeof z); // "function"};x();console.log(typeof z); // "undefined"
Call javascript function which name is in variable
window[name]()
You can call functions by name reference by selecting them as a property of window
and executing them
How to execute a JavaScript function when I have its name as a string
Don't use eval
unless you absolutely, positively have no other choice.
As has been mentioned, using something like this would be the best way to do it:
window["functionName"](arguments);
That, however, will not work with a namespace'd function:
window["My.Namespace.functionName"](arguments); // fail
This is how you would do that:
window["My"]["Namespace"]["functionName"](arguments); // succeeds
In order to make that easier and provide some flexibility, here is a convenience function:
function executeFunctionByName(functionName, context /*, args */) {
var args = Array.prototype.slice.call(arguments, 2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func].apply(context, args);
}
You would call it like so:
executeFunctionByName("My.Namespace.functionName", window, arguments);
Note, you can pass in whatever context you want, so this would do the same as above:
executeFunctionByName("Namespace.functionName", My, arguments);
What happens when JavaScript variable name and function name is the same?
Functions are a type of object which are a type of value.
Values can be stored in variables (and properties, and passed as arguments to functions, etc).
A function declaration:
- Creates a named function
- Creates a variable in the current scope with the same name as the function (unless such a variable already exists)
- Assigns the function to that variable
- Is hoisted
A var
statement:
- Creates a variable in the current scope with the specified name (unless such a variable already exists)
- Is hoisted
- Doesn't assign a value to that variable (unless combined with an assignment operator)
Both your declaration and var
statement are hoisted. Only one of them assigns a value to the variable a
.
calling a jQuery function named in a variable
If you have your function in the global scope (on the window object) you can do:
// calls function setOne, setTwo, ... depending on number.
window["set" + number]();
And using eval
will allow you to run functions in local scope:
eval("set" + number + "()");
When is JavaScript's eval()
not evil?
Related Topics
Inspect Extension's Chrome.Storage in Devtools
How to Decide When to Use Node.Js
Check If an Element Is Present in an Array
What's the Purpose of Prototype
Get the Index of the Object Inside an Array, Matching a Condition
Equivalent of String.Format in Jquery
Is Node.Js Native Promise.All Processing in Parallel or Sequentially
What Does $(Function() {} ); Do
Setting Query String Using Fetch Get Request
How to Convert Blob to File in JavaScript
How to Create a Jquery Plugin with Methods
Invoking a Function Without Parentheses
Best Way to Add Page Specific JavaScript in a Rails 3 App
Smooth Scroll to Div Id Jquery
React Context VS React Redux, When Should I Use Each One