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?
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.
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.
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.
The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand.
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]; } }); }
var name = callback.name;
MDN:
The name property returns the name of a function, or an empty string for anonymous functions:
Live DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With