459,521 Members | 1,252 Online Need help? Post your question and get tips & solutions from a community of 459,521 IT Pros & Developers. It's quick & easy.

# (new Function) as function.

 P: n/a 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. Jul 10 '06 #1
3 Replies

 P: n/a HopfZ wrote: 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 Jul 10 '06 #2

 P: n/a Janwillem Borleffs wrote: HopfZ wrote: 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.split(','),t); } function R(s){ if(/[abc]\_/.test(s)){ return new Function(['a_','b_','c_'],'return ('+s+');'); } var t = s.split('->'); return new Function(t.split(','),'return ('+t+');'); } 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')). Jul 11 '06 #3

 P: n/a "HopfZ" 'Faith without judgement merely degrades the spirit divine.' Jul 11 '06 #4

### This discussion thread is closed

Replies have been disabled for this discussion. 