Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

2/28/2013

Rethinking about function objects in javascript

Traditional way of learning about functions in javascript is that we look at  them as objects with properties and methods.

So you can write:

// function declaration
function car(){
    // some code
};

// add properties to car function
car.color = function(color){
    return "This car color is: " + color;
};

car.color("blue")  // returns "This car color is blue"


Now you have static property of car function/object.

That is something you can't find in other popular languages. In other languages,  functions are usually treated as behaviour attached to some class or object.That way, they are just serving one purpose  in the kingdom of the nouns.


The role of functions ( as objects) in javascript is pretty non conventional and unusuall. Many developers are having trouble seeing them as objects.

But other then that ( which is considered strange and liberal ) , there is one more  definition which brings totally new way of thinking  about functions.
And that is where the real power of language lives.

They can be seen as behaviour that caries data instead of data that caries behavoiur. It is a very important concept that must be well understood.

Lets look at code:

// function declaration with nested func inside
function car(){
    var color = "blue"

    return function(){
        return "This car color is: " + color;
    };

};

// call

var color = car();

color() // returns "This car color is blue";



So we have exactly same result, but what is the difference ?  This time instead of assigning static properties to function object, we created closure with nested function. That closure behaves as object,  memorizing properties from the parent scope. You can put everything in closure - objects, functions. All kind of data. Now behaviour ( nested function ) carries data around from it's environment.


Happy coding.




No comments:

Post a Comment