Javascript gets a code instance of the function name function parameter and object property name

  • 2020-03-30 02:39:10
  • OfStack

One, get the name of the function of the three implementation methods

Example 1:

One method seen in the js authority guide:

The Function prototype. GetName = Function () {
      Return this. The name | | this. The toString (). The match (/ function \ s * ([^ (] *) \ [1] (/)
}

Example 2:

Returns the name of the named function if it is named, the name of the assigned function variable if it is anonymous, and "anonymous" if it is anonymous in a closure.


     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"
    };

Use: executes this function inside the function to be investigated, passing in an argument, 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 (/^functions*(.*).*rn/.test(_text))
   {
    var _tempArr = _scriptArr[i].text.substr(0, _start).split('rn');
    return _tempArr[_tempArr.length - 1].replace(/(var)|(s*)/g, '').replace(/=/g, '');
   }
   else
    return _text.match(/^functions*([^(]+).*rn/)[1];
  }
 }
}
function a()
{
 return getFuncName(arguments.callee);
}
var b = function()
{
 return getFuncName(arguments.callee);
}
window.alert(a());
window.alert(b());

Second, js to get all the parameters of the function and the method of traversing all the property 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. A method to iterate over all the property names and values of an object


<script language="javascript">
var obj = new Object();
obj.myname = " I am a object ";
obj.pro2 = "23";
obj.pro3 = "abcdeg"; php Programmers stand 
for (items in obj){
 document.write(" attribute :"+items+" The value is  ("+ obj[items] +")");
 document.write("<br>");
}
</script>


Related articles: