Quantcast
Channel: How to execute a JavaScript function when I have its name as a string - Stack Overflow
Browsing latest articles
Browse All 38 View Live

Answer by catcher for How to execute a JavaScript function when I have its...

I like concise solutions, so come up with this more ES6 way:const executeByName = (name, originContext, ...args) => { const namespaces = name.split('.'); const func = namespaces.pop(); const...

View Article



Answer by Gigoland for How to execute a JavaScript function when I have its...

const myFnCollection = { myFnStringName: function(args) {} }; let fn = 'myFnStringName'; // 1. Recommended if (typeof window[fn] === 'function') { window[fn](args); } // 2. Recommended if (typeof...

View Article

Answer by SaidbakR for How to execute a JavaScript function when I have its...

You may place your functions names in an Array object and then call the array key respective to each function to execute it, DEMO:function captchaTest(msg){ let x = Math.floor(Math.random()*(21-1)) +1;...

View Article

Answer by vivek agarwal for How to execute a JavaScript function when I have...

Here's a bit robust and reusable solution I ended up implementing for one of my projects.A FunctionExecutor Constructor FunctionUsage:let executor = new...

View Article

Answer by snnsnn for How to execute a JavaScript function when I have its...

I don't think you need complicated intermediate functions or eval or be dependent on global variables like window:function fun1(arg) { console.log(arg);}function fun2(arg) { console.log(arg);}const...

View Article


Answer by SimoAmi for How to execute a JavaScript function when I have its...

People keep saying that eval is dangerous and evil because it can run any arbitrary code. However, if you use eval with a whitelisting approach, assuming you know all the possible function names that...

View Article

Answer by Zibri for How to execute a JavaScript function when I have its name...

Depending on where you are you can also use:this["funcname"]();self["funcname"]();window["funcname"]();top["funcname"]();globalThis["funcname"]();or, in nodejsglobal["funcname"]()

View Article

Answer by pouyan for How to execute a JavaScript function when I have its...

Here is my Es6 approach which enables you to call your function by it's name as string or it's function name and also enable you to pass different numbers of arguments to different types of...

View Article


Answer by SJ00 for How to execute a JavaScript function when I have its name...

Since eval() is evil, and new Function() is not the most efficient way to achieve this, here is a quick JS function that returns the function from its name in string.Works for namespace'd...

View Article


Answer by Hugo R for How to execute a JavaScript function when I have its...

all you have to do is use a context or define a new context where your function(s) reside.you are not limited to window["f"]();here is an example of how I use some dynamic invocation for some REST...

View Article

Answer by Leo Lanese for How to execute a JavaScript function when I have its...

let t0 = () => { alert('red0') } var t1 = () =>{ alert('red1') } var t2 = () =>{ alert('red2') } var t3 = () =>{ alert('red3') } var t4 = () =>{ alert('red4') } var t5 = () =>{...

View Article

Answer by Mac for How to execute a JavaScript function when I have its name...

Here is my contribution to Jason Bunting's / Alex Nazarov's excellent answers, where I include error checking requested by Crashalot.Given this (contrived) preamble:a = function( args ) { console.log(...

View Article

Answer by Suat Atan PhD for How to execute a JavaScript function when I have...

You can call javascript function within the eval("functionname as string") either. Like below: (eval is pure javascript function)function testfunc(){ return "hello world";}$( document...

View Article


Answer by PeterM for How to execute a JavaScript function when I have its...

There are several executeByName functions here which works fine, unless name contains square brackets - issue I ran into - as I have dynamically generated names. So above functions will fail on names...

View Article

Answer by Neo for How to execute a JavaScript function when I have its name...

Thanks for the very helpful answer. I'm using Jason Bunting's function in my projects. I extended it to use it with an optional timeout, because the normal way to set a timeout wont work. See...

View Article


Answer by KingRider for How to execute a JavaScript function when I have its...

Look basic:var namefunction = 'jspure'; // Stringfunction jspure(msg1 = '', msg2 = '') { console.log(msg1+(msg2!=''?'/'+msg2:''));} // multiple argument// Results ur...

View Article

Answer by crazycrv for How to execute a JavaScript function when I have its...

Easiest way is to access it like has element window.ClientSideValidations.forms.location_formis same as window.ClientSideValidations.forms['location_form']

View Article


Answer by Ithar for How to execute a JavaScript function when I have its name...

Without using eval('function()') you could to create a new function using new Function(strName). The below code was tested using FF, Chrome, IE.<html><body><button...

View Article

Answer by Magnus Smith for How to execute a JavaScript function when I have...

I can't resist mentioning another trick, which helps if you have an unknown number of arguments that are also being passed as part of the string containing the function name. For example:var...

View Article

Answer by nils petersohn for How to execute a JavaScript function when I have...

With ES6 you could to access class methods by name:class X { method1(){ console.log("1"); } method2(){ this['method1'](); console.log("2"); }}let x = new X();x['method2']();the output would be:12

View Article

Answer by Ruben Daddario for How to execute a JavaScript function when I have...

I think an elegant way of doing this is by defining your functions in a hash object. Then you can have a reference to those functions from the hash using the string. e.g.var customObject = {...

View Article


Answer by pmrotule for How to execute a JavaScript function when I have its...

So, like others said, definitely the best option is:window['myfunction'](arguments)And like Jason Bunting said, it won't work if the name of your function includes an...

View Article


Answer by nomæd for How to execute a JavaScript function when I have its name...

There's a very similar thing in my code.I have a server-generated string which contains a function name which I need to pass as a callback for a 3rd party library. So I have a code that takes the...

View Article

Answer by abhishekisnot for How to execute a JavaScript function when I have...

Surprised to see no mention of setTimeout.To run a function without arguments:var functionWithoutArguments = function(){ console.log("Executing...

View Article

Answer by dykstrad for How to execute a JavaScript function when I have its...

BE CAREFUL!!!One should try to avoid calling a function by string in JavaScript for two reasons:Reason 1: Some code obfuscators will wreck your code as they will change the function names, making the...

View Article


Answer by Cilan for How to execute a JavaScript function when I have its name...

To add to Jason Bunting's answer, if you're using nodejs or something (and this works in dom js, too), you could use this instead of window (and remember: eval is evil:this['fun'+'ctionName']();

View Article

Answer by DevAshish for How to execute a JavaScript function when I have its...

This is working for me:var command = "Add";var tempFunction = new Function("Arg1","Arg2", "window."+ command +"(Arg1,Arg2)");tempFunction(x,y);I hope this works.

View Article

Answer by Wolfgang Kuehn for How to execute a JavaScript function when I have...

All the answers assume that the functions can be accessed through global scope (window). However, the OP did not make this assumption.If the functions live in a local scope (aka closure) and are not...

View Article

Answer by Coley for How to execute a JavaScript function when I have its name...

Could you not just do this:var codeToExecute = "My.Namespace.functionName()";var tmpFunc = new Function(codeToExecute);tmpFunc();You can also execute any other JavaScript using this method.

View Article



Answer by Ahmet DAL for How to execute a JavaScript function when I have its...

If you want to call a function of an object instead of a global function with window["functionName"]. You can do it like;var myObject=new Object();myObject["functionName"](arguments);Example:var...

View Article

Answer by Bradley Shrader for How to execute a JavaScript function when I...

One more detail on Jason and Alex's posts. I found it helpful to add a default value to context. Just put context = context == undefined? window:context; at the beginning of the function. You can...

View Article

Answer by merqlove for How to execute a JavaScript function when I have its...

There too some very helpful way.http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspxvar arrayMaker = { someProperty: 'some value here', make: function...

View Article

Answer by Amirali for How to execute a JavaScript function when I have its...

You just need convert your string to a pointer by window[<method name>].example:var function_name = "string";function_name = window[function_name];and now you can use it like a pointer.

View Article


Answer by Alex Nazarov for How to execute a JavaScript function when I have...

Just thought I'd post a slightly altered version of Jason Bunting's very helpful function.First, I have simplified the first statement by supplying a second parameter to slice(). The original version...

View Article

Answer by Jason Bunting for How to execute a JavaScript function when I have...

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,...

View Article

Answer by annakata for How to execute a JavaScript function when I have its...

Two things: avoid eval, it's terribly dangerous and slowsecondly it doesn't matter where your function exists, "global" -ness is irrelevant. x.y.foo() can be enabled through x.y['foo']() or...

View Article


Answer by Eli Courtwright for How to execute a JavaScript function when I...

The answer to this other question shows you how to do that: Javascript equivalent of Python's locals()?Basically, you can saywindow["foo"](arg1, arg2);or as many others have suggested, you can just use...

View Article


How to execute a JavaScript function when I have its name as a string

I have the name of a function in JavaScript as a string. How do I convert that into a function pointer so I can call it later?Depending on the circumstances, I may need to pass various arguments into...

View Article
Browsing latest articles
Browse All 38 View Live




Latest Images