Tuesday 24 March 2015

What is the difference between call and apply in javascript?


What is the difference between call and apply in javascript?


In Javascript, call() and apply() are predefined methods. Both methods can be used to invoke a function & must have the owner object as first parameter. See More detail below:


apply lets you invoke the function with arguments as an array.
View Example:
            function myFunction1(a, b) {
                return a + b;
            }
            var myobj1 = new Object();
            var result1 = myFunction1.call(myobj1, 5, 6);
            console.log('Result with call function: ' + result1);



call requires the parameters be listed explicitly one by one.
View Exmple:
            function myFunction2(a, b) {
                return a + b;
            }
            myArray = [5, 6];
            var myobj2 = new Object();
             var result2 = myFunction2.apply(myobj2, myArray);   
             console.log('Result with Apply function: ' + result2);