Sunday, June 14, 2015

JavaScript function as an Object


If you have experience in JavaScript then I am sure you have heard about functions in JS are first class object. In this post I will try my best to explain about functions in JS as an object.

There are many ways to create functions in JS, you can get to know about this in this post: Number of ways to create function

We can add property in any function as we add in any object:

    var MyObj = {}; // creating object
    MyObj.prop1 = "value1"; // Added one property
    console.log(MyObj.prop1); // logs: value1

    // creating function
    function MyFun(arg1, arg2) {
        return arg1 + arg2;
    }

    // adding property in function, and function behave as an object
    MyFun.property1 = "funPropValue1";
    console.log(MyFun.property1); // logs: funPropValue1 
Above code shows that function behave in same way as object while adding new property in function.

Pass function in another function as an argument

In below code a method is passed in function argument, and it executes successfully:
    var MyObj = {};
    MyObj.prop1 = "value1";
    MyObj.logValue = function (value) {
        console.log(value);
    }

    function MyFun(arg1, argFun) {
        var myVal = 1;
        myVal++;
        argFun(myVal);
    }

    MyFun(12, MyObj.logValue); // logs: 2
As we can perform operations similar to object in functions we can say that functions are first class object in JavaScript.

No comments:

Post a Comment