Friday, December 19, 2014

call() and apply() method in JavaScript

call() and apply() method - Explicit binding

The call() method calls a function with a given "this" value and arguments provided individually.
                         
                         fun.call(thisValue, arg1, arg2, - - - -);

The apply() method calls a function with a given this value and arguments provided as an array.

                         fun.call(thisValue, [argArray]);

call and apply method tells that on whose context you want to execute the function.


person.getName.call(anotherPerson) here value of "this" inside getName() method is anotherPerson.

Arguments object do not have Array's methods but we can invoke Array's method explicitly by using call() and apply().


above two program can be done either using call() or apply() method

Where to use call() and where to use apply() method

When we don't know about number of arguments then we should use apply() method otherwise we can use call() method.


Link 1 - Explicit binding
Link 2 - Explicit binding
Link 3 - Explicit binding

No comments:

Post a Comment