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
2 Answers
Reset to default 4arguments
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
版权声明:本文标题:jquery - pass parents function arguments in a nested function? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744921009a2632293.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论