tags:

views:

42

answers:

3

Hi, I am wondering that javascript support to write the function inside another function, by one of blog. Is this really possible. In fact i have done code but doubt about this concept. please clear this concept. I a really confuse.

+4  A: 

The following is nasty, but serves to demonstrate how you can treat functions like any other kind of object.

var foo = function () { alert('default function'); }

function pickAFunction(a_or_b) {
    var funcs = {
        a: function () {
            alert('a');
        },
        b: function () {
            alert('b');
        }
    };
    foo = funcs[a_or_b];
}

foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();
David Dorward
Great example. I would add that it's important to note that functions defined inside other functions only exist in that functions scope (unless, of course, you assign a global function to it, as per this example).
Mike Sherov
+7  A: 

Is this really possible.

Yes.

   function a(x) {    // <-- function
      function b(y) { // <-- inner function
        return x + y; // <-- use variables from outer scope
      }
      return b;       // <-- you can even return a function.
   }
   a(3)(4);           // == 7.
KennyTM
Hah, you updated it and now we match.
altCognito
+2  A: 

Functions are first class objects that can be:

  • Defined within your function
  • Created just like any other variable or object at any point in your function
  • Returned from your function (which may seem obvious after the two above, but still)

To build on the example given by Kenny:

   function a(x) {
      var w = function b(y) {
        return x + y;
      }
      return w;
   };

   var returnedFunction = a(3);
   alert(returnedFunction(2));

Would alert you with 5.

altCognito