Functions as Arguments

Courtesy: jQueryFundamentals

In JavaScript, functions are “first-class citizens” and they can be assigned to variables or passed to other functions as arguments. Passing functions as arguments is an extremely common idiom in jQuery.

var myFn = function(fn) {
    var result = fn();
    console.log(result);
};
myFn(function() { return 'hello world'; }); // returns a string

 

But it doesn’t stop there. You can modify the function such that it returns an object instead (polymorphic) which is powerful.

var myFn = function(fn) {
    var result = fn();
    console.log(result);
};

myFn(function() { var myObject = {
    sayHello : function() {
        console.log('hello');
    },

    myName : 'Rebecca'
}; return myObject ; });

But  here’s the problem if you come from class-based languages. If you define multiple functions with the same name then the last one defined will be the one that actually runs. So in our case, myFn that returns myObject will be run.

There’s the rub.

In class-based languages, you think in terms of objects. In JavaScript, you think in terms of functions. But there’s no stopping you from implementing polymorphic JavaScript functions.

See this post: http://javascript.about.com/library/blpolyfunc.htm. Go figure.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s