Tuesday, March 6, 2012

JavaScript Anonymous functions

Usually we declare function in JavaScript as like
        function sum(a, b) {
            return a + b;

This is the regular practice of defining functions.
Beside there are enhanced capabilities of JavaScript which helps to override functions, define static functions, adding methods or members to an object and prototype, etc…
The same above function can be declared as

var sum = function (a, b) {
            return a + b;
Here  “sum” is the anonymous function object.
The above anonymous object can be send as a an argument to a function to invoke.
var sum = function (a, b) {
            return a + b;

        function testSum(f1, a, b) {
            return f1(a, b);
//sending function object and function arguments
alert(testSum(sum, 8, 10));

Another example of anonymous :-
    var fun2 = {
            "prop1": "hi",
            "met1": function (a, b) { return a + b; }

alert(fun2.met1(4, 5));
This is just like static  members which doesn’t require instance to be created to access members.

var fun3 = function () {
            this.met1 = function (a, b) { c = a + b; };
            this.c = 0;
            this.met2 = function () { alert(c); };
            this.toString = function () { alert("value is " + c); };

var objFun3 = new fun3();
objFun3.met1(8, 10);

To add a new function to fun3,
fun3.prototype.met4 = function () {
                alert('function 4');

fun3.prototype = { "met4": function () { alert("fun4 method 4"); } };

Ex:- Adding a new function to object (objFun3)
objFun3.met3 = function () {
                alert("object method 3");
Adding new function of object will not add to the class (function – fun3) prototype.
So a new instance or another instance of “fun3” other than “objFun3”, will not be able to invoke “met3”.

Overriding a function in object (objFun3)
objFun3.met1 = function (a, b) { return a - b; };
When the method (met1) is invoked using “objFun3” only then the above function will be invoked, otherwise for a different instance the (met1) method in “fun3” prototype is invoked.

Adding Static members,
fun3.met3 = function () { alert("fun3 method 3 1"); };

The static members are added to function (fun3) but not to the prototype.
Hence the static member can be invoked without creating instance to the function (fun3)

No comments:

Post a Comment