(new Function) as function.

H

HopfZ

How can I create a function nF such that for example
var sum = nF('a','b','return a+b');
and
var sum = new Function('a','b','return a+b');
do the same?

function nF(){
return new Function(arguments);
} // won't work. because Function expects first argument to be a
string, not an agruments list.

function nF(){
return (new Function).apply(null,arguments);
} // won't work. (new Function) is not a function.

var nF = Function; // wont' work.
 
J

Janwillem Borleffs

HopfZ said:
How can I create a function nF such that for example
var sum = nF('a','b','return a+b');
and
var sum = new Function('a','b','return a+b');
do the same?

function fn(args, body) {
return new Function(args, body);
}

var f = fn(['a','b'],'return a+b');
alert(f(1,2,3));


JW
 
H

HopfZ

Janwillem said:
HopfZ said:
How can I create a function nF such that for example
var sum = nF('a','b','return a+b');
and
var sum = new Function('a','b','return a+b');
do the same?

function fn(args, body) {
return new Function(args, body);
}

var f = fn(['a','b'],'return a+b');
alert(f(1,2,3));


JW

Thanks.

I wanted to make functions R and D that work as below.

/* t.
R('a_+b_*c_') returns function(a_,b_,c_){return (a_+b_*c_);}
R('x,y,z->(x+y)/z') returns function(x,y,z){return ((x+y)/z);}
D('if(b_) print(a_)') returns function(a_,b_){if(b_) print(a_)};
D('x,y->if(y) print(x)') returns function(x,y){if(y) print(x)};
R meaning Return, and D meaning Do, a_,b_,c_ meaning first, second and
third argument.
*/
function D(s){
if(/[abc]\_/.test(s)){
return new Function(['a_','b_','c_'],s);
}
var t = s.split('->');
return new Function(t[0].split(','),t[1]);
}

function R(s){
if(/[abc]\_/.test(s)){
return new Function(['a_','b_','c_'],'return ('+s+');');
}
var t = s.split('->');
return new Function(t[0].split(','),'return ('+t[1]+');');
}

I was stuck because I didn't know that (new Function('a','b','return
a+b')) can be alternatively written as (new Function(['a','b'],'return
a+b')).
 
L

Lasse Reichstein Nielsen

HopfZ said:
I was stuck because I didn't know that (new Function('a','b','return
a+b')) can be alternatively written as (new Function(['a','b'],'return
a+b')).

That's a coincidence, actually.
What you can write is
new Function("a,b","return a+b;")
Passing an array as first parameter just means that it is implicitly
converted to a string, which gives the same effect as joining with ",".
I.e.,
new Function(["a","b"],"return a+b;")
is equivalent to
new Function(["a","b"].join(","),"return a+b;")
which is againg the same as the first function above.

/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top