5月15日
JavaScript – Platform for Web 2.0
I was excluded JavaScript in the "Web 2.0 basic things" intentionally, because JavaScript is the only choice for every web pages. But most of us know and/or use half the feature of JavaScript. JavaScript has more than these. Lot of frameworks which target Web 2.0 and applications utilize these smart features. I would like to share some of these features which make JavaScript as a platform for Web 2.0 applications.
If you know these, please have a look and share your knowledge.
Before getting into these, keep the following statement in your mind about JavaScript:
"Anything can be defined within the context of anything and assigned it to anything".
Confused?
Let's take an example, you can define a class from a function and enumerate its properties as array elements. And, you can treat an array as a object, function as data, etc. The following sections briefs about this.
Lamda Functions
Lamda functions are unnamed functions which can be assigned to a variable like assigning an expression. This is more or less similar to functional programming style. See the following example:
var square = function(x){return x*x;}
alert(square(2)); // returns 2 * 2 = 4
Code Snippet 1
The square is actually a variable on which the function reference with the above signature has been assigned.
What is the difference between normal named functions and lamda functions?
Let us see the below code snippets:
var square = function(x){return x*x;}
function twoSquare(square)
{
return square * 2;
}
alert(twoSquare(square(3))); // returns 9 * 2 = 18
Code Snippet 2
In the above example, the lamda function "square" is passed as argument to "twoSquare" function as function reference. See the body of "twoSquare". It treats the function "square" as a variable.
Also, you can assign or treat lamda function to object property and array element. The developers of "C" family can enjoy this feature.
The lamda function simulates the C++ or C# style class declaration when creating a class. See the Code Snippet 3.
function Customer(title, firstName)
{
this.title = title;
this.firstName = firstName;
this.getName = function(){return this.title + " " + this.firstName.toUpperCase();}
}
var amid = new Customer("Mr","Amid");
alert(amid.getName()); // returns Mr AMID
Code Snippet 3
In code snippet 3, a class Customer has been defined. In this getName is a lamda function. Remember, getName is variable to the function reference.
Let us see other features in succeeding articles.