How do I call a dynamically-named method in Javascript?
Solution 1
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);
Solution 2
As Triptych points out, you can call any global scope function by finding it in the host object's contents.
A cleaner method, which pollutes the global namespace much less, is to explicitly put the functions into an array directly like so:
var dyn_functions = [];
dyn_functions['populate_Colours'] = function (arg1, arg2) {
// function body
};
dyn_functions['populate_Shapes'] = function (arg1, arg2) {
// function body
};
// calling one of the functions
var result = dyn_functions['populate_Shapes'](1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions.populate_Shapes(1, 2);
This array could also be a property of some object other than the global host object too meaning that you can effectively create your own namespace as many JS libraries such as jQuery do. This is useful for reducing conflicts if/when you include multiple separate utility libraries in the same page, and (other parts of your design permitting) can make it easier to reuse the code in other pages.
You could also use an object like so, which you might find cleaner:
var dyn_functions = {};
dyn_functions.populate_Colours = function (arg1, arg2) {
// function body
};
dyn_functions['populate_Shapes'] = function (arg1, arg2) {
// function body
};
// calling one of the functions
var result = dyn_functions.populate_Shapes(1, 2);
// this works as well due to the similarity between arrays and objects
var result2 = dyn_functions['populate_Shapes'](1, 2);
Note that with either an array or an object, you can use either method of setting or accessing the functions, and can of course store other objects in there too. You can further reduce the syntax of either method for content that isn't that dynamic by using JS literal notation like so:
var dyn_functions = {
populate_Colours:function (arg1, arg2) {
// function body
};
, populate_Shapes:function (arg1, arg2) {
// function body
};
};
Edit: of course for larger blocks of functionality you can expand the above to the very common "module pattern" which is a popular way to encapsulate code features in an organised manner.
Solution 3
I would recommend NOT to use global
/ window
/ eval
for this purpose.
Instead, do it this way:
define all methods as properties of Handler:
var Handler={};
Handler.application_run = function (name) {
console.log(name)
}
Now call it like this
var somefunc = "application_run";
Handler[somefunc]('jerry');
Output: jerry
Case when importing functions from different files
import { func1, func2 } from "../utility";
const Handler= {
func1,
func2
};
Handler["func1"]("sic mundus");
Handler["func2"]("creatus est");
Solution 4
you can do it like this:
function MyClass() {
this.abc = function() {
alert("abc");
}
}
var myObject = new MyClass();
myObject["abc"]();
Solution 5
I wouldn't recommend using the window as some of the other answers suggest. Use this
and scope accordingly.
this['yourDynamicFcnName'](arguments);
Another neat trick is calling within different scopes and using it for inheritance. Let's say you had nested the function and want access to the global window object. You could do this:
this['yourDynamicFcnName'].call(window, arguments);
![Ahmed Aboelyazeed](https://lh4.googleusercontent.com/-ZJI5bAEh--A/AAAAAAAAAAI/AAAAAAAAADk/peuJlzA_lHk/photo.jpg?sz=256)
Comments
-
Ahmed Aboelyazeed almost 2 years
I am working on dynamically creating some JavaScript that will be inserted into a web page as it's being constructed.
The JavaScript will be used to populate a
listbox
based on the selection in anotherlistbox
. When the selection of onelistbox
is changed it will call a method name based on the selected value of thelistbox
.For example:
Listbox1
contains:Colours
Shapes
If
Colours
is selected then it will call apopulate_Colours
method that populates anotherlistbox
.To clarify my question: How do I make that
populate_Colours
call in JavaScript? -
Ahmed Aboelyazeed about 15 yearsThanks for the response. The 'window' bit really threw me until I googled it and found that global objects are part of the window object. Now it makes sense! Thank you. FYI I found a good page about it here devlicio.us/blogs/sergio_pereira/archive/2009/02/09/…
-
Ahmed Aboelyazeed about 15 yearsThat's a nice way of keeping it clean. How would I call the method though? Would window[dyn_functions['populate_Colours'](arg1, arg2) work?
-
David Spillett about 15 yearsAs epascarello points out, you usually don't need "window" - "dyn_functions['populate_Colours'](arg1,arg2);" will work. In fact not including the global object's name will make code more portable if you are writing routines that might ever be used in a JS environment other than a web browser. There is an exception to this though: if you have a local variable called dyn_functions in a function then you would need to be more specific which you are referring to, but this situation is best avoided (by having sensible naming conventions) anyway.
-
codecraig about 13 yearsI did something similar except the functions I was targeting were in the jQuery "fn" namespace. For example,
$.fn[method_prefix + method_name](arg1, arg2);
-
David Sherret over 10 yearsSince this post is from '09 you probably know this by now, but you're creating an array, then assigning to the array's properties (not indexes). You might as well do
var dyn_functions = {};
so you don't needlessly create an array... this isn't a huge issue though. -
Lee Goddard almost 10 yearsNice. Worth adding a
try
/catch
block, perhaps. -
Stan Smulders over 8 yearsThis may be obvious to some, but for those that can't get it to work: throw the function outside your
$(function () {
andwindow.load
code :) -
brianlmerritt over 8 yearsuncaught reference error - functionName is not defined
-
Sizzling Code over 6 yearsHow to call this type of functions dynamically?
alertify.[dynamicFunctionName](var);
?? -
GoldBishop over 6 yearsoverly complicated answer but does work. I would think the resource load for scenario where I have series of patterned functions and i need a decision tree to choose the execution, this method might be overly complex to perform the task. Albeit, if I was wiring up my own class object, this would be the preferred approach to defining the object itself.
-
GoldBishop over 6 years@brianlmerritt you have to define the value for
functionName
...the answerer made the assumption that you already had that defined. -
GoldBishop over 6 yearsWhat are the implications of using this pattern? I have read that the
eval
function has some wierd side-effects related to its use. I generally try to stay away from it, unless it is a last resort. -
Peter Chaula almost 6 yearsWhy can't you use
['alert']('Hi')
since the window namespace is the default namespace? -
Sebastian Simon almost 6 years@peter Because square brackets are not property accessors in this context, but denote an Array. Arrays are not functions, so you can’t call them.
-
Sebastian Simon almost 6 years@SizzlingCode You can’t use dot notation and bracket notation at the same time.
-
Valentine Shi over 5 yearsWhy nobody raised the issue of polluting the global object? Especially with such generic names. Beware, this approach will bite you seriously as you build the system comprising more than 2-3 external libs.
-
kinsley kajiva about 5 yearsread this post stackoverflow.com/questions/19417274/…
-
JCH77 over 4 yearsIt seems new Function() cannot be used like that for this purpose.
-
zookastos about 4 yearsThis is more generic and better than having global functions in window object.
-
MeatPopsicle over 2 yearsEval'ing dynamic content makes it very easy for a hacker to inject and execute their own code into yours
-
Ramon Dias over 2 yearswhy NOT to use
global
/window
/eval
? -
pride over 2 yearsHow can I do it typescript? I have a method in class, which will iterate array of object, which has functionName and function argument. To be called functions are present in same class. However I get error as this[functionName](funcArgument) is not a function
-
Tim over 2 yearsCan you share a codepen example? With classes make sure to think about lexical scope.
-
Greggory Wiley about 2 yearsThank you for this! Simple fundamental answer, works in all types of js, maybe missing { following class User ?
-
Greggory Wiley about 2 yearsWIll you add an example for doing this when window does not exist like in Node?
-
Tim about 2 yearsThe window doesn't have to exist, I just gave that as an example. You can use any object, and from my memory I think node does have a global
this
scoped to their own object, so the first option should work perfectly in node or the browser.