Home > Web Front-end > JS Tutorial > Code examples for javascript to obtain function names, function parameters, and object attribute names_Basic knowledge

Code examples for javascript to obtain function names, function parameters, and object attribute names_Basic knowledge

WBOY
Release: 2016-05-16 16:52:22
Original
973 people have browsed it

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(/functions*([^(]*)(/)[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 an anonymous function in a closure, "anonymous" is returned.

Copy code The code is as follows:

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]; Function, pass in one parameter, which is arguments.callee. function ee(){
//
var fnname =getFnName(arguments.callee)
//
alert(fnname)
};
ee();


Copy code


The code is as follows:


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)

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());




There is another situation that cannot be solved by the above method. I hope someone who has a solution can give some advice.




Copy code


The code is as follows:


var x = 
{ 

 run: function()

{

return getFuncName(arguments.callee);

}

}
window.alert(x.run()); In this case, the name of the function cannot be obtained;





Copy the code


The code is as follows:

function test(){

for(var i=0;i document.write(arguments[i]); }

2. Method to traverse all attribute names and values ​​of an object

Copy code Code As follows:



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template