1. Three implementation methods for obtaining function names
Example 1:
A method seen in the js authoritative guide :
Function.prototype.getName = function(){ return this.name || this.toString().match(/function\s*([^(]*)\(/)[1] }
Example 2:
If the current function is a named function, its name is returned. If it is an anonymous function, the assigned function variable name is returned. If it is Anonymous functions in closures return "anonymous".
var getFnName = function(callee){ var _callee = callee.toString().replace(/[\s\?]*/g,""), comb = _callee.length >= 50 ? 50 :_callee.length; _callee = _callee.substring(0,comb); var name = _callee.match(/^function([^\(]+?)\(/); if(name && name[1]){ return name[1]; } var caller = callee.caller, _caller = caller.toString().replace(/[\s\?]*/g,""); var last = _caller.indexOf(_callee), str = _caller.substring(last-30,last); name = str.match(/var([^\=]+?)\=/); if(name && name[1]){ return name[1]; } return "anonymous" };
Usage: Execute this function inside the function to be investigated, passing in one parameter, which is arguments.callee.
function ee(){ //+++++++++++++++++++++++++++++++++ var fnname =getFnName(arguments.callee) //+++++++++++++++++++++++++++++++++ alert(fnname) }; ee();
Example 3:
function getFuncName(_callee) { var _text = _callee.toString(); var _scriptArr = document.scripts; for (var i=0; i<_scriptArr.length; i++) { var _start = _scriptArr[i].text.indexOf(_text); if (_start != -1) { if (/^function\s*\(.*\).*\r\n/.test(_text)) { var _tempArr = _scriptArr[i].text.substr(0, _start).split('\r\n'); return _tempArr[_tempArr.length - 1].replace(/(var)|(\s*)/g, '').replace(/=/g, ''); } else return _text.match(/^function\s*([^\(]+).*\r\n/)[1]; } } } function a() { return getFuncName(arguments.callee); } var b = function() { return getFuncName(arguments.callee); } window.alert(a()); window.alert(b());
2. js method of obtaining all parameters of a function and traversing all attribute names and values of an object
1. Get all parameters
function test(){ for(var i=0;i<arguments.length;i++) document.write(arguments[i]); }
2. Method to traverse all attribute names and values of an object
<script language="javascript"> var obj = new Object(); obj.myname = "我是对象"; obj.pro2 = "23"; obj.pro3 = "abcdeg"; php程序员站 for (items in obj){ document.write("属性:"+items+"的值是 ("+ obj[items] +")"); document.write("<br>"); } </script>
The above is the detailed content of Detailed explanation of how to obtain function name and parameter method instance in javascript. For more information, please follow other related articles on the PHP Chinese website!