[Javascript] Various types to create functions - I am confused

liorean liorean at gmail.com
Thu Oct 4 06:16:18 CDT 2007


On 04/10/2007, JS Student <tuofamerikazmostwanted at gmail.com> wrote:
> These are the various methods to create functions in JavaScript:
>
> var foo = new Function();

Function constructor call, this is here in order that you can compile
a function at runtime.

> var bar = Function();

Function function call, this translates into a constructor call, in
other words it's the same as above.

> var baz = function() {}

Function expression/initialiser/literal. This exists in order to
provide practical lambda expressions with lexical scope.

> function zag() {}

Function declaration, this exists to provide functions bound to
variable names at compile time in order to allow
use-before-declaration. (Bad idea...)






> My question is why there so many ways to do one task? Do these methods
> serve some specific purpose or is it just redundancy?

Mostly redundancy, though at least these two ways of declaring
functions are necessary:


* Function expressions:

The function declaration

    function fn(){}

is equal to:

    var fn=function fn(){};

where the declaration has been moved to the top of the scope, before
any other variable declarations.


* Function constructor calls

The Function constructor call is necessary to allow runtime
compilation of strings into functions. However, there is a slight
overlap with eval and function expressions/declarations.

    var fn=new Function();

can be thought of as an equivalent to

    var fn=eval('(function(){})');

or to

    eval('function fn(){}');

However, that misses one crucial detail about the Function constructor
call - the Function constructor call produces a function that does not
participate in the scope chain where the call was made, in difference
to eval. In other words, eval requires the engine to allow scope
augmentation which negatively affects performance, where Function
constructor calls don't.
-- 
David "liorean" Andersson



More information about the Javascript mailing list