rabidmachine9
rabidmachine9

Reputation: 7975

pass parents function arguments in a nested function?

I am having a problem with arguments object in a nested function, seems like arguments.length is taken from parent function while arguments[0] is taken from nested function... anybody can explain why this is happening ?and show me the most effective way to pass parent foo's arguments to bar?

$.fn.foo = function(color1, color2, time ){
    return this.each(function bar(){

        for(var i = 0;i < (arguments.length - 1);i++){
            alert(arguments.length); //this is taken from foo function and returns 2   
        alert(arguments[i]); //this is taken from  bar 

        }
    });
    };

Upvotes: 1

Views: 3975

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328594

Simple solution: Get a local reference to arguments.

$.fn.foo = function(color1, color2, time ){
    var args = arguments; // Create a private reference
    return this.each(function bar(){
        alert(args.length); //Use private reference
    });
};

Upvotes: 3

davin
davin

Reputation: 45525

arguments will always (unless changed) have the scope of the currently executing function, which in your case is bar.

Read the jquery .each docs, the function "prototype" is as follows:

.each( function(index, Element) )

So of course arguments.length will return 2. Whether or not you have named variables to catch those 2 sent arguments is another story, but the arguments object will have length 2 if the function was called with 2 arguments.

Upvotes: 4

Related Questions