O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  



Using arguments.caller for recursion and debugging
Macromedia incorrectly documented this powerful function. After investigation I found it had useful applications in reference to recursive algorithms and debugging.

Contributed by:
Unknown User anonymous2
[01/30/04 | Discuss (1) | Link to this hack]

Using "arguments.caller" Macromedia's Documentation: "Property; refers to the Arguments object of the calling function. " In actuality, arguments.caller returns a reference to the calling function. Therefore one can implement double function recursion by calling arguments.caller(). Example: function a () { trace("(a) level "+ ++z); arguments.caller(); } function b () { trace("(b) level "+ ++z); a(); } b(); This is an example of infinite regression: The output window will contain: ---------------------------------------------- (b) level 1 (a) level 2 (b) level 3 ... (b) level 253 (a) level 254 (b) level 255 256 levels of recursion were exceeded in one action list. This is probably an infinite loop. Further execution of actions has been disabled in this movie. ---------------------------------------------- Arguments.caller can also be used to find the name of the function you are in. This is useful for debugging because one can have error messages that include the problematic method. Example: findName = function (scope){ for(var i in scope){ if(scope[i] == arguments.caller) return i; } return false; } function test() { trace(findName(this)); } test(); This algorithm steps through the scope object that function resides in. It then checks if the element in that object matches the function reference of the calling function (ie. the function that you want its name). If the condition is met, the name is returned. The output window will contain: ---------------------------------------------- test ---------------------------------------------- Note: arguments.callee() which can be used to recursively call an anonymous function is synonymous to this[findName(this)]().


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.