Get Function Name in JavaScript

Get function name in JavaScript

function test() {  alert(arguments.callee.name); } 
b = test;
b();

outputs "test" (in Chrome, Firefox and probably Safari). However, arguments.callee.name is only available from inside the function.

If you want to get name from outside you may parse it out of:

b.toString();

but I think name property of function object might be what you need:

alert(b.name);

this however does not seem work for IE and Opera so you are left with parsing it out manually in those browsers.

Javascript : getting function name with this.name

That comes from Function.name as explained in the JS MDN

A Function object's read-only name property indicates the function's
name as specified when it was created, or "anonymous" for functions
created anonymously.

function doSomething() {}
doSomething.name; // "doSomething"

Can I get the name of the currently running function in JavaScript?

In ES5 and above, there is no access to that information.

In older versions of JS you can get it by using arguments.callee.

You may have to parse out the name though, as it will probably include some extra junk. Though, in some implementations you can simply get the name using arguments.callee.name.

Parsing:

function DisplayMyName() 
{
var myName = arguments.callee.toString();
myName = myName.substr('function '.length);
myName = myName.substr(0, myName.indexOf('('));

alert(myName);
}

Source: Javascript - get current function name.

get the current function name in javascript

This -

var my_arguments;

function MyFunction() {
my_arguments = arguments;

$.ajax({
type: "POST",
url: "http://www.google.com",
dataType: "json",
data: "foo=bar",
error:function(XMLHttpRequest, textStatus, errorThrown) {
alert(my_arguments.callee.name);
},
success: function(jsonObject) {
//do something
}
});
}

is what you need.

The arguments inside the error function refers to this method's own arguments object. It does not refer to the MyFunction's arguments object. That's why you are getting error:MyFunction. Using a global variable in this case provides you a workaround to this problem.

Also, to get only the name of the function, you need to use arguments.callee.name. arguments.callee will give you a reference to the calling function, not a function name in string.

How can I get the name of function inside a JavaScript function?

I think that you can do that :

var name = arguments.callee.toString();

For more information on this, take a look at this article.

function callTaker(a,b,c,d,e){
// arguments properties
console.log(arguments);
console.log(arguments.length);
console.log(arguments.callee);
console.log(arguments[1]);
// Function properties
console.log(callTaker.length);
console.log(callTaker.caller);
console.log(arguments.callee.caller);
console.log(arguments.callee.caller.caller);
console.log(callTaker.name);
console.log(callTaker.constructor);
}

function callMaker(){
callTaker("foo","bar",this,document);
}

function init(){
callMaker();
}

Get Javascript function name

As mentioned, the function doesn't have any intrinsic name other than the "" it gets from being an anonymous function. Some browsers (Firefox, probably Chrome, maybe others) do however perform some limited form of static analysis to figure out names of declared functions, to help with error stack traces. You can get to it in an relatively cross-browser way by getting setMsg to throw an exception and then parse exc.stack:

// cheat with .% in Firebug; there might be other ways of doing this, I dunno:
yt.setMsg.%m.za.__defineSetter__('a', function() { throw new Error(); });

try { yt.setMsg('a', 'a'); }
catch(e) { alert(e.stack.split('\n')[2].split('@')[0]); }

... On the other hand, this is a pretty terrible hack and dependent on the actual function involved (and if you know the function, you probably know its name already). It does work a bit more reliably when done from inside the function.

If you restrict yourself to just Firefox and are doing this for debug purposes, there are better ways of getting to it. Set devtools.chrome.enabled to true in about:config, open a Scratchpad (Shift+F4), set it to environment: browser, and run the following:

Components.utils.import("resource://gre/modules/jsdebugger.jsm");
window.addDebuggerToGlobal(window);

dbg = new Debugger();
dw = dbg.addDebuggee(content);

f = content.wrappedJSObject.yt.setMsg;
name = dw.makeDebuggeeValue(f).displayName;

dbg.removeDebuggee(content);

alert(name);

In both cases, you will note that it alerts "m.ya" instead of "setMsg", and indeed this is because the function was originally declared as m.ya = function() { ...; }. There is no reason why "setMsg" would be a preferable name, from the point of the browser.

Dynamic function name in javascript?

As others mentioned, this is not the fastest nor most recommended solution. Marcosc's solution below is the way to go.

You can use eval:

var code = "this.f = function " + instance + "() {...}";
eval(code);

Get current function name in strict mode

For logging/debugging purposes, you can create a new Error object in the logger and inspect its .stack property, e.g.

function logIt(message) {    var stack = new Error().stack,        caller = stack.split('\n')[2].trim();    console.log(caller + ":" + message);}
function a(b) { b()}
a(function xyz() { logIt('hello');});


Related Topics



Leave a reply



Submit