String to function name in javascript

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

Calling a function from a string, stored in a variable can be done in two different ways. The first approach makes use of the window object method, and the second method makes use of the eval() function.

This tutorial will guide you to learn the way to execute a JavaScript function using its name as a string.

Using the window[]() Method

Here, to execute the function using the function name as a string, the string should be changed to a pointer using the following syntax.

Syntax

var functionName = "string"; functionName = window[functionName]( parameters );

Here we have stored a string as a function name, and this value is called using window[].

Algorithm

  • STEP 1 − Define a function to display the output
  • STEP 2 − Define another function and assign the name of the output function as a string in a global variable. If required, a parameter can be passed on to the output function.
  • STEP 3 − Now call this global variable inside window[], which executes the output function.

Example

In the below example, showOutput is the function defined to display the output. winObjFunc is defined to perform window[] action towards the showOutput function name stored in the global variable strFunc. Using the syntax above, the showOutput function is called and we get the function executed.

html> body> h2>Using the i>window object/i> method to execute function with its string name./h2> p id="namStrDisp">/p> script> function showOutput(output) document.getElementById('namStrDisp').innerHTML = output; > function winObjFunc() strFunc = "showOutput"; outStr = 'Output by the window object'; window[strFunc](outStr); > winObjFunc(); /script> /body> /html>

Using the eval() Method

To execute the function using the function name as a string, eval() can be used. In this case, the arguments to the function can be a statement, an expression, variables, properties of existing objects, or a sequence of expressions. Follow the syntax below to use this method. The only drawback with this method is that this has limited browser support and it’s considered to be obsolete.

Syntax

Users can follow the syntax below to use the eval() method to call function.

Similar to the window object method, a string function name is sent as an argument to the eval() method.

Example

In the below example, evalOutput is the output function defined. The global variable evalStr stores this function with parameters as a string. Using the syntax explained above, eval() calls this string value in the variable, and we get the output function running.

html> body> h2>Using the i>eval()/i> method to execute function with its string name./h2> p id="evlStrDisp">/p> script> function evalOutput(info) document.getElementById('evlStrDisp').innerHTML = info; > function evalFunc() evalStr = "evalOutput('eval method here')"; eval(evalStr); > evalFunc(); /script> /body> /html>

In this tutorial, we have understood the two ways to execute the JavaScript function when we have its name as a string.

The window object method is the most commonly used method. eval() method is depreciated and not recommended.

Источник

How to Call a JavaScript Function From a String Without Using eval

eval is evil in JavaScript! The MDN eval page states:

Obsolete
This feature is obsolete. Although it is still supported by browsers, its usage is discouraged in new projects. Try to avoid using it.

eval executes a string containing code, e.g.

eval("var x = 'Hello from eval!';"); console.log(x);

eval raises several issues:

  1. Security: your string can be injected with other commands by third-party scripts or user input.
  2. Debugging: it’s difficult to debug errors — you have no line numbers or obvious points of failure.
  3. Optimization: the JavaScript interpreter cannot necessarily pre-compile the code because it could change. While interpreters have become increasingly efficient, it’ll almost certainly run slower than native code.

Unfortunately, eval is very powerful and it’s easy for less experienced developers to overuse the command.

Despite the warnings, eval still works — even in Strict Mode — but you can normally avoid it. In the past it was primarily used for de-serializing JSON strings but we now have the safer JSON.parse method.

However, what if we have a function name in a string, e.g.

// function we want to run var fnstring = "runMe"; function runMe()  // do stuff >

How do we execute the runMe() function without using eval ? I recently encountered this situation when using the HTML5 History API; the pushState method won’t permit you to store a direct reference to a function so you need to define its name as a string. You could also face similar challenges using Web Workers or any other API where objects are serialized.

The simplest and safest execution-without-eval solution is a range of conditions, e.g.

// function we want to run var fnstring = "runMe"; switch (fnstring)  case "functionX": functionX(); break; case "functionY": functionY(); break; case "functionZ": functionZ(); break; case "runMe": runMe(); break; >

It’s safe, but fairly inefficient and painful to write if you have dozens of possible function calls.

A better solution is to use the window object which references the current window and all items within it. We can check whether fnstring is available as an object within window and run it if it’s a function, e.g.

// function we want to run var fnstring = "runMe"; // find object var fn = window[fnstring]; // is object a function? if (typeof fn === "function") fn();

You can perform other checks if necessary to ensure the function has an expected name.

What if the function we want to call has parameters — perhaps stored in an array? No problem; we simply use the apply method:

// function name and parameters to pass var fnstring = "runMe"; var fnparams = [1, 2, 3]; // find object var fn = window[fnstring]; // is object a function? if (typeof fn === "function") fn.apply(null, fnparams);

So that’s another reason to stop using eval . As a bonus, this solution is safer, less error prone, easier to debug and will normally execute faster. I hope it helps.

Share This Article

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he’s been advocating standards, accessibility, and best-practice HTML5 techniques. He’s created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He’s written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Источник

How to transform a String into a function in JavaScript?

We have given a string and need to convert it into a function in JavaScript. Sometimes, we get mathematical or function expressions in the form of the string, and executing that expression, requires converting strings into the function expression. In this tutorial, we will learn different approaches to converting the given string into a functional or mathematical expression.

Use the eval() method

The eval() method takes the expression as a parameter and evaluates the expression. For example, if we pass the ‘2 + 2’ string as a parameter of the eval() method, it returns 4 as it evaluates the mathematical expression 2+2.

It also evaluates the function expression as like the mathematical expression.

Syntax

Users can follow the syntax below to use the eval() method to convert a string into a function in JavaScript.

In the above syntax, we have passed the function string as a parameter of the eval() method.

Example 1

In the example below, we created the string containing the function expression. The function expression prints the message on the webpage.

After that, we passed the string as a parameter of the eval() method, and then we have executed the func() function as we call the normal function.

The func() function gives the same output as the normal function.

  

Using the eval() method to convert a string into the function expression in JavaScript.

Example 2

In the example below, we have created the object, and getHeight property of the object contains the function in the string format

We have used the eval() method to evaluate the string value of the getHeight property and stored it inside the getHeight property again after converting the function string to expression.

After that, we executed the getHeight() function, which returns the height that we have stored in the height variable.

  

Using the eval() method to convert a string into the function expression in JavaScript.

Using the Function Constructor

The Function() constructor allows us to create a function from the string. The Function() constructor can take N parameters. The first N-1 parameter of the Function constructor() works as a parameter of the function to be created, and the Nth parameter is function expression

Syntax

Users can follow the syntax below to use the Function() constructor to create a function from the string.

let func = new Function(expression);

In the above syntax, func is created using the Function() constructor. The expression is a string containing the function expression.

Example 3

In the example below, we have created the expression string. We also evaluate mathematical expression using the eval() method in the expression string.

After that, we invoked the func() function like the normal function, and users can observe the output

  

Using the Function() constructor to convert a string into the function expression in JavaScript.

Example 4

We have passed the multiple parameters to the Function() constructor in the example below. The first three parameters work as a parameter of function expression passed as a fourth parameter.

We print the parameter values in the function expression. In the output, users can see that it prints the default values of parameters as we haven’t passed any parameters while invoking the concatString() function.

  

Using the Function() constructor to convert a string into the function expression in JavaScript.

In this tutorial, we learned to convert string to function expression using two different approaches. In the first approach, we have used the eval() method, which we can use to evaluate any expression in JavaScript.

In the second approach, we have used the Function constructor, which takes the function parameters and function expression as a parameter to create a new function.

Источник

Читайте также:  Заголовок страницы
Оцените статью