Wednesday, May 11, 2011

javascript function practices that hardly used in other language

Function in javascript is nothing but object. That means we can create functions dynamically, assign them to other variables, pass them as parameters of other functions. Function's role in javascript is quite special. And some practices are never seen in other programming languages.

1. Functions that Return Functions

function func() {
   alert('A!');

   //return a function!
   //well, we can just think we return an object
   return function(){
      alert('B!');
   };
}

//alert A
var b = func();
//alert B
b();



In the example, the outside function func() wraps a returned function, so it creates a closure, and we can use this closure to store private data, which is accessible by the returned function but not to the outside code. Let's see another example:

var setup = function () {
    //we have a counter, when setup is called,
    //the counter is set to 0
    var counter = 0;
    //the return function can access counter, 
//but outside code cannot see it.
    return function () {
       return (counter += 1);
    };
};
// usage
var next = setup();
next(); // returns 1
next();  //returns 2
next();  //returns 3

This example is a counter that gives you an incremented value every time you call it.


2. Self-Defining Functions(Functions rewrite themself!)

var itIsWeird = function() {
      alert('javascript function is weird');
      //rewrite itself now!!!!
      itIsWeird = function() {
           alert('it is not that weird');
      };
}
//first time call the function, 
//it shows javascript function is weird
itIsWeird();

//call the function again, 
//it shows it is not that weird
itIsWeird();


Self-Defining functions could be useful when your function has some initial preparatory work to do and it needs to do it only once(maybe some init job?). Because there’s no reason to do repeating work when it can be avoided, a portion of the function may no longer be required. In such cases, the self defining function can update its own implementation. It can obviously help with the performance of your application, because your redefined function simply does less work.

These practices are hardly seen in other languages. Well, but it doesn't mean they are good practices. Take self-defining functions as example. Yes they may be useful in some cases. But a function changes its own behavior by itself? One thing i always stress is we should try to minimize things that could possibly bring confusions in software engineering, and i think self-defining function is one the things we should try to avoid. And its benefits, well, i believe we can achieve in other ways that are more readable and easier to understand.

No comments: