Wednesday, May 25, 2011

javascript function property

Javascript functions are objects, so they can have properties and methods. Actually, they do. When you create a function, the function has a length property that indicates the number of arguments the function expects. A very simple example:

var getUserById = function(id) {
     var user = {id : id};
     //do other tasks
     return user;
}
//show 1
console.log(getUserById.length);

Another usage of function property is we can cache the result of a function, so we don't have to repeat the same computation again & again.

var calculation = function(seed) {
    if (!calculation.cache[seed]) {
        //do some expensive calculation based on seed
        var result = (seed * seed * 3 + 15) / 3.14;
        calculation.cache[seed] = result;
        console.log('calculation is done for ' + seed);
    }
    return calculation.cache[seed];
};

calculation.cache = {};

//you can see console log 'calculation is done for 3'
var testOne = calculation(3);
//you won't see console log because the result is return directly from cache.
var testTwo = calculation(3);

No comments: