How do I call a dynamically-named method in Javascript?
Assuming the populate_Colours
method is in the global namespace, you may use the following code, which exploits both that all object properties may be accessed as though the object were an associative array, and that all global objects are actually properties of the window
host object.
var method_name = "Colours";
var method_prefix = "populate_";
// Call function:
window[method_prefix + method_name](arg1, arg2);
How to call a function using a dynamic name in JS
Usually we should avoid eval. What you are trying to do is possible without using eval too and with a simpler code :
//variables
var ta = 3213;
var da = 44;
var s = [];
//Create string representation of function
s[1] = function test0(){ alert(" + da + "); };
s[0] = function test1(){ alert(" + ta +"); };
s.forEach((fun) => { this[fun.name] = fun;});
// calling the function
this["test"+1]();
Or simple in your code do :this["test"+1]();
EDIT: If you are using string and eval just because you are getting function name as string, instead you can create an object :
var data = {};
for(var i = 0; i<10; i++) {
data['key'+ i] = function (i) { alert(i); }.bind(null, i);
}
Dynamic function name in javascript?
As others mentioned, this is not the fastest nor most recommended solution. Marcosc's solution below is the way to go.
You can use eval:
var code = "this.f = function " + instance + "() {...}";
eval(code);
How do I call a dynamically-named method with for in Javascript
If the functions are globally accessible you may write
window['a'+i]()
Otherwise, you may be able to rewrite your code to add all the functions to one variable:var f = {
a1: function() { },
a2: function() { },
a3: function() { }
};
... and call f['a'+i]()
.If you're rewriting, since all functions are named by an index, you might as well write:
var myFunctions = [
function() { },
function() { },
function() { }
];
... and call myFunctions[i]()
. (Of course, as Felix Kling points out in comments, i
here would have to be adjusted to be 0-based). Javascript Dynamic Function Call with Name
Since you want to call functions using bracket notation in object scope, not window scope, you can use this
instead of window
:
function meth_4()
{
this["meth_1"]();
this["meth_2"]();
this["meth_3"]();
}
Dynamic function names in JavaScript
Updated answer in 2016:
The "However, that's changing..." part of the original answer below has changed. ES2015 ("ES6") was released a year ago, and JavaScript engines are now finally coming into compliance with one of its lesser-known aspects: Function#name
.
As of ES2015, this function has a name despite being created using an "anonymous" function expression:
var f = function() { };
Its name is f
. This is dictated by the specification (or the new one for ES2016) in dozens of different places (search for where SetFunctionName
is used). In this particular case, it's because it gets the name of the variable it's being assigned to. (I've used var
there instead of the new let
to avoid giving the impression that this is a feature of let
. It isn't. But as this is ES2015, I'll use let
from now on...)Now, you may be thinking "That doesn't help me, because the f
is hardcoded," but stick with me.
This function also has the name f
:
let obj = {
f: function() { }
};
It gets the name of the property it's being assigned to (f
). And that's where another handy feature of ES2015 comes into effect: Computed property names in object initializers. Instead of giving the name f
literally, we can use a computed property name:let functionName = "f";
let obj = {
[functionName]: function() { }
};
Computed property name syntax evaluates the expression in the []
and then uses the result as the property name. And since the function gets a true name from the property it's being assigned to, voilà, we can create a function with a runtime-determined name.If we don't want the object for anything, we don't need to keep it:
let functionName = "f";
let f = ({
[functionName]: function() { }
})[functionName];
That creates the object with the function on it, then grabs the function from the object and throws the object away.Of course, if you want to use lexical this
, it could be an arrow function instead:
let functionName = "f";
let f = ({
[functionName]: () => { }
})[functionName];
Here's an example, which works on Chrome 51 and later but not on many others yet:// Get the namelet functionName = prompt( "What name for the function?", "func" + Math.floor(Math.random() * 10000));
// Create the functionlet f = ({ [functionName]: function() { }})[functionName];
// Check the nameif (f.name !== functionName) { console.log("This browser's JavaScript engine doesn't fully support ES2015 yet.");} else { console.log("The function's name is: " + f.name);}
Related Topics
Loading Local Files with JavaScript Without a Web Server
Can't Set Innerhtml on Tbody in Ie
How to Trigger Click on Page Load
How to Add My Own Methods to HTMLelement Object
Implementing or in Firestore Query - Firebase Firestore
How to Get Ssl Certificate Details Using JavaScript
Get Unique Results from JSON Array Using Jquery
Understanding JavaScript Immutable Variable
JavaScript Contenteditable - Set Cursor/Caret to Index
How to Execute a Function on Pressing the Enter Key in an <Input> Field
Jquery Attr('Checked','Checked') Works Only Once
How to Pass Jsf Managed Bean Properties to a JavaScript Function
Angularjs Communication Between Directives
How to Adapt Trampolines to Continuation Passing Style
Executing Code at Page-Level from Background.Js and Returning the Value
How to Replace Last Occurrence of Characters in a String Using JavaScript