Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JavaScript Function with Parameters from Array

Tags:

javascript

I'd like to create a function object in JavaScript from a string in an automated way, but I'm struggling a little with parameters. What I can do so far is the following:

var objectStr = "function(x) { return x; }";
var myFunc = Function("x", "{ return x; }");

If I make some assumptions, that the function will always start with "function(x)" I can do:

var objectStr  = "function(x) { return x;}";
var funcBody = objectStr.replace("function(x)", "");
var myFunc = Function("x", funcBody);

This gets me close to an automatic approach. I could also assign the string "x" to a value and pass that in as my parameter. However I really want to get to a place where I can provide the following:

var objectStr = "function(x, y) { return x*y; }";

At this point I want to extract out the parameters, x and y into a string array. I'm sure I could do this with regex quite sensibly.

var parameters = [ "x", "y" ];

But the question is, how do I now create a function, with multiple parameters, from my array of parameters?

EDIT

The reason for wanting to do this is to generate a function, for a callback. I have no control over the values of these parameters. A jQuery example to illustrate (although this isn't the library I'm using) might be:

// Define myFunc using approach above
// then somewhere later in 3rd party code an itterator block
// like below will call:
jQuery(data).each(function() {
    myFunc(this);
}
like image 846
Ian Avatar asked Feb 16 '26 00:02

Ian


1 Answers

var parsedParameters = ["x", "y"];
var parsedBody = "return x*y";
var func = Function.apply(null, parsedParameters.concat(parsedBody));
    /*function anonymous(x,y) {
        return x*y
    }*/

It works because:

http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.1

15.3.1 The Function Constructor Called as a Function

When Function is called as a function rather than as a constructor, it creates and initialises a new Function object. Thus the function call Function(…) is equivalent to the object creation expression new Function(…) with the same arguments.

So one doesn't have to use new, which enables the use of .apply. .apply is used to call a function with the arguments coming from an array. See Function#apply

The array in the example passed to .apply after .concat is:

["x", "y", "return x*y"]

So the static equivalent is new Function("x", "y", "return x*y")

like image 158
Esailija Avatar answered Feb 18 '26 13:02

Esailija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!