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

Robert Van Dam rvandam00 at gmail.com
Thu Oct 4 01:43:11 CDT 2007


I think a lot of the redundancy here comes from javascripts multiple
inheritance from a lot of other languages.  The first two ways are the same
as far as I'm aware and are vestiges of Java's "EverythingIsAnObject"
syndrome.  In another sense, they are the underlying form of the last two
because they are syntactically the simplest: they don't add any syntax to
the language.

The other two are syntactic sugar and very sweet at that.

var baz = function() {} is technically a first class function sometimes
referred to as a closure (although I prefer to use that term to refer to the
act of enclosing other variables inside of it).  In javascript jargon I
think this is most commonly referred to as an anonymous function.  As you
are using it here, it's not really anonymous, you've just split the process
of creating and naming the function into two pieces.  However, this syntax
is great for something like this:

document.addEventListener("mousedown", function(event) { doSomething(event)
}, false);

in which case you do have a truly anonymous function (even though its mostly
a dummy wrapper for doSomething).

The last form of course is the standard function creation form and it just
simplifies the anonymous form so that creation and naming happen together.
It saves you typing and is more familiar to people who've never worked in a
language that allows you to pass around functions like any other value
(unfortunately, there's more that don't than do).

Does that answer your question?

Rob

On 10/4/07, JS Student <tuofamerikazmostwanted at gmail.com> wrote:
>
> These are the various methods to create functions in JavaScript:
>
> var foo = new Function();
> var bar = Function();
> var baz = function() {}
> function zag() {}
>
> My question is why there so many ways to do one task? Do these methods
> serve some specific purpose or is it just redundancy?
>
> Thanks
> _______________________________________________
> Javascript mailing list
> Javascript at lists.evolt.org
> http://lists.evolt.org/mailman/listinfo/javascript
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.evolt.org/pipermail/javascript/attachments/20071004/227eaa36/attachment.htm>


More information about the Javascript mailing list