JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
April 30, 2010

MooTools’ .attempt(), arguments, and Javascript’s apply()

arguments is a local object variable available within any function in JavaScript. Arguments can be accessed as shown in foo() below.

function foo(){
    console.debug(arguments); // ['a', 'b']
    console.debug(arguments[0]); // 'a'
}

foo('a', 'b');

This is convenient for functions that may need to accept an arbitrary number of parameters. But if these arguments need to again be passed on to a 2nd function from within the first, a problem arises:

function foo(){
    // ...
    bar(arguments);
}

function bar(){
    console.debug(arguments[0]); // ['a', 'b']
    console.debug(arguments[1]); // undefined
    // ...
}

foo('a', 'b');

Notice that arguments[0] in bar() above now contains an array of the arguments passed to foo(), while arguments[1] is undefined. MooTools has an .attempt function prototype (See the documentation) that fixes this issue.

function foo(){
    // ...
    bar.attempt(arguments); # Call bar() using MooTools attempt()
}

function bar(){
    console.debug(arguments[0]); // 'a'
    console.debug(arguments[1]); // 'b'
    // ...
}

foo('a', 'b');

Looking at MooTools 1.3b1.1 Source, the arguments are passed to the requested function using apply() (See the documentation).

Tags: Mootools javascript code