4

I'm working with animation in JavaScript, and I have a bunch of functions you can call to add things to the animation queue. Basically, all of these functions look like this:

function foo(arg1, arg2) {
    _eventQueue.push(function() {
        // actual logic
    }
 }

I'm wondering now if it would be possible to cut down on this boilerplate a little bit, though, so I don't need that extra "_eventQueue" line in each function body dozens of times. Would it be possible, for example, to make a helper function which takes an arbitrary function as an argument and returns a new function which is augmented to be automatically added to the event queue? The only problem is that I need to find a way to maintain access to the function's original arguments in this process, which is... complicated.

1 Answer 1

3

You're looking for the arguments identifier, which gives an array-like object containing the arguments that were passed to the current function.

For example:

function createEnqueuer(func) {
    return function() {
        var outerArgs = arguments;

        _eventQueue.push(function() {
            return func.apply(window, outerArgs);
        });
    };
}
Sign up to request clarification or add additional context in comments.

6 Comments

Dang, beat me to it. However, I'm not sure I agree with calling apply with this set to window. Although this code currently follows existing JavaScript convention (by matching what this is set to when you call a function not as a method), it provides little benefit, and it is subject to change in EMCAScript 5. If I'm not mistaken, this will be set to undefined instead. Disclaimer: I am by no means an expert on this subject; I just so happened to watch this yesterday: yuiblog.com/blog/2010/02/24/video-crockonjs-3 .
Can you see any potential issues with calling func.apply(this, outerArgs)?
Awesome... how does this work? I would have assumed that the arguments array would hold the arguments to the createEnqueuer function, not to the func function.
@thurn: The arguments keyword gives the arguments of whatever function it's referenced in. (even if the function doesn't declare any arguments)
@SLaks: Oh! I get it. 'arguments' refers to the arguments of the anonymous function you return, but it's invoked with all of the arguments of the original function. I was confused because I forgot you didn't have to declare all of a function's arguments in the signature... you can just pass them in and access them via the arguments array. That is some cool stuff!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.