On Sun, Jul 17, 2011 at 2:26 AM, Matthew Bramer <[email protected]> wrote:
> So, I'm taking away from your answer that I should in general use .call
> I have to tell you, I have a hard time following what you have said though.
> I'm pretty new to this stuff, so some of your answer is clearly above my
> knowledge level. Sometimes, I wish I had an easy button for JS. :/
> Cheers,
> Matt
Ok, let me try ;)
Let's say you have a function with three parameters, foo bar baz ->
function boo(foo,bar,baz){ alert(foo+bar+baz); }
Now `call` and `apply` allow you to set the "context" (`this` value)
of a function, that's what the first parameter is for. But let's skip
that for now (I use `null` for it).
Then the only difference left between `call` and `apply` is that apply
will map the second parameter (which must be an array) onto the
function parameters of the original function. On the other hand, call
will pass them on 1:1 from the second argument you pass on to it
onwards. In example:
boo.call(null, 1, 2, 3); -> alerts 123
boo.call(null, "hello", 5, "world"); -> alerts hello5world
boo.apply(null, [1,2,3]); -> alerts 123
boo.apply(null, ["hello", 5, "world"]); -> alerts hello5world
Mind you, `apply` ignores any other parameters, just looks at the
second parameter (the array) !
boo.apply(null, [1,2], 3); -> alerts 12undefined
So part of the usefulness of `call` and `apply` is passing on
parameters from an array. The usages for this are usually a bit higher
level so I won't bother you with them :)
- peter
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]