David Golightly wrote:
re****@gmail.com wrote:
<snip>
>var func = new Function("var me = <selfRef>; alert(me.params);");
func.params = "This is a test parameter";
window.setTimeout(func, 500);
<snip>
1. Do not use "new Function('<function code>')" when you
know all the details of a function before runtime.
This is not a reasonable statement as it disregards the possibility that
the desired outcome may be multiple unique function objects created in a
way that avoided the creation of closures.
This has all the drawbacks of using eval:
Not by any means. It may have many of the drawbacks of - eval - but
using the Function constructor does not result in the direct execution
of its string argument, and also allows some control over the
environment in which the string of code used is executed (the
potentially independent provision of formal parameters for the function
and the mixing of that string with other code that may, for example,
mask out sensitive aspects of the global environment).
it's hugely inefficient.
That very much depends on the environment. In IE6 the use of the
Function constructor can be the fastest method of creating a function
object (which is significant for people writing for an IE only context
and needing performance.
I'm disappointed to see that the
CLJ FAQ still has a lot of code examples using "new Function"
when the function constructor
var func = function(args) { /* code */ }
or
function func(args) { /* code */ }
is preferred.
<snip>
Preferred by whom, and why? The code for those FAQ entries originate at
a time when inner functions were not well supported (as they were not
formally specified until ECMA 262 3rd Edition.). That makes them old but
they have not stopped working (or being less well supported) in the
meanwhile. Previous discussions on the subject have never exposed any
technical justification for changing them, just vague personal
pretences. While switching to using inner functions means forming
closures, and so in many cases having to write additional code to
mitigate IE's memory leak problem.
Blanket injunctions without justification are very dangerous things.
They tend to leave some people doing things without understanding why
they are doing them. As with most things, what should be 'preferred' is
a good technical understanding of how javascript behaves. That allows
people to make informed design decisions about what is appropriate in
their specific context.
Richard.