Javascript Jems - Lambda expressions
Thursday, 08 July 2010 00:00
Article Index
Javascript Jems - Lambda expressions
Using anonymous functions and invocation

A more familiar alternative

As Javascript also support anonymous functions you can even write this example as:

list.sort(function(a,b)
{return a.length-b.length;});

This last example looks a lot more like the sort of typical use that lambda expression are put to in other languages.

Banner

Of course there is nothing stopping you from creating your own functions that accept other functions. For example:

Say=function(t)
{
t();
}

This will simply call any function that you pass to it. If you define:

Hello=function()
{
alert("Hello");
}

Then

Say(Hello);

will call the Hello function and display an alert.

Notice that you have to pass the variable that stores the function without accidentally invoking it first.

For example don’t write:

Say(Hello());

by mistake as this would call the Hello function and then pass its result to the Say function.

You need to distinguish very clearly between passing a function and passing the result of a function to another function.

Function invocation ()

You also need to get into the habit of thinking of the () brackets as being the function invocation operator. When ever you use () following an expression it calls the function that is the result of the expression.

For example you can write:

(Say)(Hello);

or even:

Say=function(t)
{
t();
}(Hello);

The round brackets at the end of the function definition call the function as soon as it has been defined. This instant function evaluation can be useful when you want to pass the result of a lambda expression.

For example:

alert(function sum(a,b){return a+b;}(1,2));

Here we have a lambda expression, the sum function being defined and evaluated in a single step.

The result, 3 in this case is passed to the alert function.

Although this example isn’t particularly useful it does become useful when combined with other Javascript features such as closure – more of which another time.

Banner


Task.js Asynchronous Tasks In JavaScript

There are some interesting things going on the latest version of JavaScript and already some new uses are being found for them. Task.js uses the new generator facility to build an asynchronous task fa [ ... ]



jQuery UI Custom Control - Widget Factory

So you have been using jQuery and jQuery UI but you have a few custom JavaScript controls that don't work in the same way. The solution is to create a jQuery UI custom control so that you can use ever [ ... ]


Other Articles

<ASIN:0596805527>

<ASIN:0470684143>

<ASIN:0137054890>

<ASIN:1449381871>

<ASIN:1430230541>

 



Last Updated ( Monday, 09 August 2010 16:38 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2013 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.