calling Function constructor with parameters

13 May

If eventually you would want to use Function constructor it can be handy to decline formal parameters as a comma separated string.

As the ECMAScript-262 says it is permissible but not necessary to have one argument for each formal parameter to be specified. For example, all three of the following expressions produce the same result:

new Function('a', 'b', 'c', 'return a+b+c')
new Function('a, b, c', 'return a+b+c')
new Function('a,b', 'c', 'return a+b+c')

For instance, if you have an array with parameter names you want to pass to the function, you can do the following:

var f = new Function(arrayName.join(','),"function body"); 

It’s not recommended to use Function constructor as it significantly increases the time to create a function, but sometimes it could be useful.

Leave a comment

Posted by on May 13, 2009 in JavaScript


Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: