What is this.initialize.apply(this, arguments);

2,047 views
Skip to first unread message

damerub

unread,
Jul 16, 2009, 1:21:46 PM7/16/09
to Prototype & script.aculo.us
Could someone explain what the following line does?

this.initialize.apply(this, arguments);


I know how 'apply' works, but I cannot understand why 'this' is used
twice here? both 'this' refer to the same object (current object).
then why not just call this.initialize(arguments)?. What's the
difference here?


THANKS IN ADVANCE!

Lin



T.J. Crowder

unread,
Jul 17, 2009, 3:18:27 AM7/17/09
to Prototype & script.aculo.us
Hi Lin,

this.initialize(arguments) would call the initialize method and pass
in an array of arguments as the first and only parameter to the
function. (Well, on many browsers 'arguments' isn't quite a real
array, but very similar to one.) this.initialize.apply(this,
arguments) calls the initialize method passing it the set of arguments
in the 'arguments' array as *individual* arguments.

So:

* * * *

var a = [1, 2, 3];

this.function(a);
// => Passes the function a single argument that's an array, [1,2,3]

this.function.apply(this, a);
// => Passes the function three individual arguments 1, 2, and 3

* * * *

You have to use the second 'this' because the JavaScript apply
function requires the context (the value to use for "this" during the
call) as the first argument, and then the arguments array as the
second argument. (It needs this for a good reason -- it doesn't have
access to the value otherwise, because of the way "this" works in
JavaScript.)

HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available

damerub

unread,
Jul 28, 2009, 12:44:55 PM7/28/09
to Prototype & script.aculo.us
Hi, T.J.

Thank you for the explainnation. It's very clear.

best regards,

Lin
Reply all
Reply to author
Forward
0 new messages