How to Turn a String into a JavaScript Function Call

How to turn a String into a JavaScript function call?

Seeing as I hate eval, and I am not alone:

var fn = window[settings.functionName];
if(typeof fn === 'function') {
fn(t.parentNode.id);
}

Edit: In reply to @Mahan's comment:
In this particular case, settings.functionName would be "clickedOnItem". This would, at runtime translate var fn = window[settings.functionName]; into var fn = window["clickedOnItem"], which would obtain a reference to function clickedOnItem (nodeId) {}. Once we have a reference to a function inside a variable, we can call this function by "calling the variable", i.e. fn(t.parentNode.id), which equals clickedOnItem(t.parentNode.id), which was what the OP wanted.

More full example:

/* Somewhere: */
window.settings = {
/* [..] Other settings */
functionName: 'clickedOnItem'
/* , [..] More settings */
};

/* Later */
function clickedOnItem (nodeId) {
/* Some cool event handling code here */
}

/* Even later */
var fn = window[settings.functionName];
/* note that settings.functionName could also be written
as window.settings.functionName. In this case, we use the fact that window
is the implied scope of global variables. */
if(typeof fn === 'function') {
fn(t.parentNode.id);
}

Is there a way to create a function from a string with javascript?

I added a jsperf test for 4 different ways to create a function from string :

  • Using RegExp with Function class

    var func = "function (a, b) { return a + b; }".parseFunction();

  • Using Function class with "return"

    var func = new Function("return " + "function (a, b) { return a + b; }")();

  • Using official Function constructor

    var func = new Function("a", "b", "return a + b;");

  • Using Eval

    eval("var func = function (a, b) { return a + b; };");

http://jsben.ch/D2xTG

2 result samples:
Sample Image
Sample Image

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);

Given a string describing a Javascript function, convert it to a Javascript function

There's also the Function object.

var adder = new Function("a", "b", "return a + b");

How do I convert a string to a function reference in JavaScript?

You get the function reference from the window object:

var fn = window[function_as_string];

Demo: http://jsfiddle.net/Guffa/nA6gU/

Vue.js 2: converting a string in a function call at an event handler

Try to create one method, which will be working with all buttons

new Vue({
el: "#app",
data: {
myArray: [
{ value: 1, fn: "firstMethod" },
{ value: 2, fn: "secondMethod" },
],
},
methods: {
basicMethod(name) {
console.log(`'${name}' was executed.`);
if(name === 'firstMethod') {
//some logic, and so on for other methods if u need
}
},
},
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app">
<template v-for="elem in myArray">
<button @click="basicMethod(elem.fn)"> <!-- Here is where I am stucked. -->
<!-- <button> -->
{{elem.value}}
</button>
</template>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script src="script.js"></script>
</body>
</html>

Convert string (was a function) back to function in Javascript

var func = new Function(theFunctionString);
func();

MDN:

new Function ([arg1[, arg2[, ... argN]],] functionBody)

Parameters

arg1, arg2, ... argN
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".

functionBody
A string containing the JavaScript statements comprising the function definition.


Update:

All this a very bad practice!

You should have a generic function that get parameters that build what you want. The only thing that change are the parameters. Store those parameters in the DB you have.

Call javascript function encoded in a string

Your functionString contains exactly the string

"function (message) { console.log(message); }"

Evaluating it as-is does present JavaScript engine with incorrect syntax (there is no name for this function). JavaScript expects construct like function <name>(<params>) { }. Alternatively, you can use anonymous function (i.e. no name present), but only as a parameter or in a context of evaluating expression. The minimal typical evaluating expression would be (function() {})() If you want to get fancy, !function() {} is also ok - the exclamation mark in front turns it into boolean expression that requires function evaluation before negating the output.

So, in your example this will work:

eval("("+functionString+")('abc')");

because then you do anonymous function call - something JavaScript can live with.

Alternatively, you can also use just brackets, then you need to assign the result to something you can use later:

var foo = eval("("+functionString+")");
foo('ddd');

Here is a little proof / playground to learn about it:
http://jsfiddle.net/Exceeder/ydann6b3/

Call a JavaScript function name using a string?

Property accessors can be used to access any object's properties or functions.

If the function is in the global scope, you can get it using the window object:

var myFunc = window[myFuncName];

This also works within the this scope:

var myFunc = this[myFuncName];


Related Topics



Leave a reply



Submit