这个脚本假设无处不在。它允许从函数本身中获取任何函数的名称 。 < html> < head> ; < title>功能名称< / title> < meta http-equiv =" Content-Type" content =" text / html; charset = iso-8859-1"> < script type =" text / javascript"> ; 函数测试(){ var myName = getFunctionName(arguments.callee); alert(myName); } 函数getFunctionName(f){ var tmp = f.toString(); var re = /(\ * * function\s +)(\ w +)(\ s * \()/ m; re.exec(tmp); 返回RegExp。$ 2; } < / script> < / head> < body bgcolor =" #FFFFFF" onload =" test()"> < / body> < / html>
解决方案2; } < / script> < / head> < body bgcolor =" #FFFFFF" onload =" test()"> < / body> < / html> 过去我发现这种方法不适用于匿名 函数(根据定义!)。 var anon = function() { var myName = getFunctionName(arguments.call * ee); alert(myName); }; anon();
< Baconbutty写道:过去我发现这种方法不适用于匿名函数(根据定义!)。 var anon = function() {my myName = getFunctionName(arguments.call * ee); alert(myName); }; anon();
但它如何为匿名函数工作?匿名 函数没有名字,这就是为什么它们是匿名的! getFunctionName将在这种情况下返回字符串anonymous,并且 它是真实的真相。 我可以把它改成一些getNameOrNameIt,所以它会在现场克隆 匿名函数并给它们起名字,但它会这是一个全新的故事。 为什么?
And this script supposes to work everywhere. It allows to get the name of any function from within the function itself. <html> <head> <title>Function name</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript"> function test() { var myName = getFunctionName(arguments.callee); alert(myName); } function getFunctionName(f) { var tmp = f.toString(); var re = /(\s*function\s+)(\w+)(\s*\()/m; re.exec(tmp); return RegExp.$2; } </script> </head> <body bgcolor="#FFFFFF" onload="test()"> </body> </html>
解决方案 2; } </script> </head> <body bgcolor="#FFFFFF" onload="test()"> </body> </html> In the past I have found that approach does not work for anonymous functions (by definition!). var anon=function() { var myName = getFunctionName(arguments.call*ee); alert(myName); }; anon(); Baconbutty wrote: In the past I have found that approach does not work for anonymous functions (by definition!). var anon=function() { var myName = getFunctionName(arguments.call*ee); alert(myName); }; anon();But how does it suppose to work for anonymous functions? Anonymous functions do not have names, this is why they are anonymous! getFunctionName will return in such case the string "anonymous", and it''s holly truth. I could change it into some getNameOrNameIt, so it would clone anonymous functions on the spot and give them names, but it would be the whole new story. And why?
更多推荐
getFunctionName v1.0
发布评论