23 May, 2011

Javascript Functions Flexibility

In Javascript, everything is an object. Functions in Javascript are said to be first-class objects, that can be passed as arguments to other functions, stored as variables, created at run-time,etc.

Anonymous functions without parameters that run immediately.

(function() {
var one = 1;
var two = 2;
alert(one+two);
})();

In above anonymous function, the parenthesis at the end indicates that this function will be run immediately without being assigned to any variable.

Anonymous functions with parameters that run immediately.
The parenthesis at the end can have some parameters as well. Such as,

(function(one, two) {
alert(one+two);
})(1, 2);

Or, if you want to assign the value to some variable then,

var three = (function(one, two) {
alert(one+two);
})(1, 2);
alert(three); //and output is 3


Assign Attribute to Functions in Javascript
In Javascript we can modify classes after they have been defined and objects after they have been created. Lets take an analogy, we have a car class,

function Car(name, model) {
this.name = name;
this.model = model;
}
Car.prototype = {
getName: function() {
return this.name;
},
getModel: function() {
return this.model;
}
}
//instantiate the class now
var benz = new Car('Benz', 1969);
var bmw = new Car('Bmw', 1984);

//now modify the class
Car.prototype.getPrice = function() {
return "Price for " + this.getName() + "is " + 20000;
};

//now modify the specific object instance
benz.showPrice = function() {
alert(this.getPrice());
};

In above example, we added a new function getPrice() after two object instances for the class are created. And, benz object instance gets showPrice() function in addition to other functions of the class, but bmw object instance wont get the showPrice() function in this case. This feature is called Object Mutability.
This is just few examples that tend to focus on flexibility of javascript functions.

No comments: