Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

please explain the apply and call methods in javascript [duplicate]

Tags:

javascript

Possible Duplicate:
What is the difference between call and apply?

What is the main difference between apply and call methods... I go through the web but unable to find the best solution.. Please help me friends...

like image 552
Mihir Avatar asked Dec 13 '22 17:12

Mihir


2 Answers

Every function in JavaScript receives two objects in addition to the default parameters. These are this and arguments. The value of this is determined by it's invocation pattern. apply or call can be used to invoke a function and provide it a default this object.

This will be very useful in many situations. For example, arguments is an array-like object, but not really an Array with all the useful Array methods. So, to apply an Array method slice on arguments, you can do this:

Array.prototype.slice.apply(arguments, [1, 2])

Had arguments been an object of Array type, you could have used

arguments.slice(1, 2) 

call is nothing but a modified version of apply. See elusive's comment.

Mr.Douglus Crockford gives a very good introduction to JavaScript functions in this video: Function the Ultimate.

like image 188
dheerosaur Avatar answered Apr 28 '23 02:04

dheerosaur


The main difference is that call accepts a list of arguments, where arguments after the first one are passed directly to the method:

myFunc.call(thisObj, arg1, arg2, arg3);

Whereas apply accepts only two arguments - the first is the this object and the second is an array of arguments to pass to the method:

myFunc.apply(thisObj, [arg1, arg2, arg3]);

apply is often used in a situation where you want to pass the arguments object, which contains a list of arguments passed to the current function, to another method:

function myOtherFunc(arg1, arg2, arg3) {
    if (typeof arg1 == "object" && arg1 !== null)
        myFunc.apply(this, arguments);
}
like image 20
Andy E Avatar answered Apr 28 '23 01:04

Andy E