On Jul 17, 9:14 am, Matthew Bramer <remym...@gmail.com> wrote:
> I've been watching some appendTo videos and I came across a video with this
> code sample in it:
>
> var obj1 = { ping: "pong" }, myfunc = function(append) {
> console.log([this.ping, append].join(" ")); } myfunc.apply(obj1,
> ["something", "else"]);
> pong something
>
> var obj1 = { ping: "pong" }, myfunc = function(append) {
> console.log([this.ping, append].join(" ")); } myfunc.call(obj1,
> ["something", "else"]);
> pong something,else
>
> I played around with these two methods and realized .apply will only accept
> an array. However, .call will accept an array as well. What is the
> difference between these two methods and why would I use .apply when .call
> allows me to pass strings as well as arrays?

The difference is that when you use call, the array is *the* formal
parameter. When you use apply, each element of the array is a
parameter.

so given:

    var args = [x, y];

then

    someFn.call(null, args);

is the same as:

    someFn(args);

but

    someFn.apply(null, args);

is the same as

    someFun(x, y);

The main reason for using apply is so that an arguments object can be
passed. This is useful when you don't know how many arguments will be
used, so you just pass them all as arguments. Or you can convert it to
an array and then reorder or remove them as required, then pass the
array.


--
Rob

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/jsmentors@jsmentors.com/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/jsmentors@googlegroups.com/

To unsubscribe from this group, send email to
jsmentors+unsubscr...@googlegroups.com

Reply via email to