admin管理员组

文章数量:1405512

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 

        }
    });
    };

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 

        }
    });
    };
Share Improve this question asked Apr 29, 2011 at 10:01 rabidmachine9rabidmachine9 7,98511 gold badges47 silver badges59 bronze badges 2
  • Just out of curiosity, is there a reason you pass a named function bar into the each function, instead of just an anonymous one? – Zirak Commented Apr 29, 2011 at 10:08
  • 2 @Zirak, presumably to make the question clear and to be able to refer to the function by its name. It's actually a great idea for that reason! – davin Commented Apr 29, 2011 at 10:12
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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
    });
};

本文标签: jquerypass parents function arguments in a nested functionStack Overflow