Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name as String from a Javascript function reference?

Tags:

javascript

I want to do the opposite of Get JavaScript function-object from its name as a string?

That is, given:

function foo() {}  function bar(callback) {   var name = ???; // how to get "foo" from callback? }  bar(foo); 

How do I get the name of the function behind a reference?

like image 471
Gili Avatar asked May 16 '12 17:05

Gili


People also ask

How can I call a function given its name as a string?

There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.

How do you call a function name my function in JavaScript?

Define a function named "myFunction", and make it display "Hello World!" in the <p> element. Hint: Use the function keyword to define the function (followed by a name, followed by parentheses). Place the code you want executed by the function, inside curly brackets. Then, call the function.

Is string passed by reference in JavaScript?

In fact, Strings in Javascript are indeed passed “by reference”. Thus, calling a function with a string does not involve copying the string's contents. However, JavaScript Strings are immutable; in contrast to C++ strings, once a JavaScript string has been created it cannot be modified.

What does %% mean in JavaScript?

The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand.


2 Answers

If you can't use myFunction.name then you can:

// Add a new method available on all function values Function.prototype.getName = function(){   // Find zero or more non-paren chars after the function start   return /function ([^(]*)/.exec( this+"" )[1]; }; 

Or for modern browsers that don't support the name property (do they exist?) add it directly:

if (Function.prototype.name === undefined){   // Add a custom property to all function values   // that actually invokes a method to get the value   Object.defineProperty(Function.prototype,'name',{     get:function(){       return /function ([^(]*)/.exec( this+"" )[1];     }   }); } 
like image 125
Phrogz Avatar answered Oct 26 '22 09:10

Phrogz


var name = callback.name; 

MDN:

The name property returns the name of a function, or an empty string for anonymous functions:

Live DEMO

like image 29
gdoron is supporting Monica Avatar answered Oct 26 '22 08:10

gdoron is supporting Monica