开发者

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(argumen开发者_开发问答ts.length); //this is taken from foo function and returns 2   
        alert(arguments[i]); //this is taken from  bar 

        }
    });
    };


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜